blfuentes
blfuentes

Reputation: 2827

Good practice for Request and Request.Form in asp.net webpages 2

I'm reading some tutorials about asp.net webpages 2 and I found something confusing

In this page: http://www.asp.net/web-pages/tutorials/working-with-pages/validating-user-input-in-aspnet-web-pages-sites the following code:

<form method="post">
    @Html.ValidationSummary()
    <div>
        <label for="coursename">Course name: </label>
        <input type="text" name="coursename" value="@Request["coursename"]" />
        @Html.ValidationMessage("coursename")
   </div>
...

Is it "correct" to use in this case just Request["fieldname"] instead of Request.Form["fieldname"]? I understand(please correct if wrong) that request will also check for fields in the querystring while request.form will only check within the form's fields.

Might this create any kind of errors/security problems... is a good or bad use of request...?

Upvotes: 2

Views: 5322

Answers (2)

Kevin Brechb&#252;hl
Kevin Brechb&#252;hl

Reputation: 4727

If you request a value with @Request[key], then the framework search for a value in the following steps (if nothing was found, it goes to the next step):

  1. Request.QueryString[key]
  2. Request.Form[key]
  3. Request.Cookies[key]
  4. Request.ServerVariables[key]

But I think it's a better option to directly get your value from the collection you want it from. It's better for the security of our app and also better for the maintenance.

Update: I've written a blog post about this on my blog.

Upvotes: 2

tlbignerd
tlbignerd

Reputation: 1114

It is correct to use either way, either Request.Form or simply Request to pull the value from the QueryString. The only issue you might encounter is if you have a querystring and form field with the same name. In both cases though you should already be testing and validating the data on the server to handle any errors. A user could edit the Request.Form object before it goes to the server almost as easy as if they could edit the querystring. At a minimum you should have:

<input type="text" name="coursename" value="@Server.UrlEncode(Request["coursename"])" />

ASP.Net MVC uses the Request method by default when mapping values to the parameters of the action being run in a controller. So it seems to be good enough for Microsoft to use Request["coursename"].

Upvotes: 2

Related Questions