开发者

ASP.NET MVC ignoring Content-Length?

开发者 https://www.devze.com 2023-01-31 04:47 出处:网络
I\'ve been having some problems with missing post data in ASP.NET MVC which has lead me to investigate how ASP.NET MVC deals with invalid content lengths. I had presumed that a post with a invalid con

I've been having some problems with missing post data in ASP.NET MVC which has lead me to investigate how ASP.NET MVC deals with invalid content lengths. I had presumed that a post with a invalid content leng开发者_StackOverflow社区th should be ignored by MVC.NET but this doesn't seem to be the case.

As an example, try creating a new ASP.NET MVC 2 web application and add this action to the HomeController:

public ActionResult Test(int userID, string text)
{
    return Content("UserID = " + userID + " Text = " + text);
}

Try creating a simple form that posts to the above action, run fiddler and (using "Request Builder") modify the raw data so that some of the form data is missing (e.g. remove the text parameter). Before executing the request, remember to un-tick the "Fix Content-Length header" checkbox under the Request Builder options then set a break point on the code above and execute the custom http request.

I find that the request takes a lot longer than normal (30 seconds or so) but to my amazement is still processed by the controllers action. Does anyone know if this is expected behavior and, if so, what would you recommend to safeguard against invalid content-lengths?


ASP.NET does not ignore the Content-Length request header. Consider the following controller action as an example which simply echoes back the foo parameter:

[HttpPost]
public ActionResult Index(string foo)
{
    return Content(foo, "text/plain");
}

Now let's make a valid POST request to it:

using (var client = new TcpClient("127.0.0.1", 2555))
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
    writer.Write(
@"POST /home/index HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:2555
Content-Length: 10
Connection: close

foo=foobar");
    writer.Flush();
    Console.WriteLine(reader.ReadToEnd());
}

As expected this prints the response HTTP headers (which are not important) and in the body we have foobar. Now try reducing the Content-Length header of the request:

POST /home/index HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:2555
Content-Length: 5
Connection: close

foo=foobar

Which returns a single f in the response body. So as you can see an invalid HTTP request could lead to incorrect parsing of the parameters.

0

精彩评论

暂无评论...
验证码 换一张
取 消