Why is Json Request Behavior
needed?
If I want to restrict the HttpGet
requests to my action I can decorate the action with the [HttpPost]
attribute
Example:
[HttpPost]
public JsonResult Foo()
{
return Json("Secrets");
}
// Instead of:
public JsonResult Foo()
{
return Json("Secrets", JsonRequestBehavior.AllowGet);
}
Why isn't [HttpPost]
sufficient?
Why the framework "bugs" us with the JsonRequestBehavior.AllowGet
for every JsonResult
that we have. If I want to deny get requests I'll add the HttpPost
attribute.
MVC defaults to DenyGet
to protect you against a very specific attack involving JSON requests to improve the liklihood that the implications of allowing HTTP GET
exposure are considered in advance of allowing them to occur.
This is opposed to afterwards when it might be too late.
Note: If your action method does not return sensitive data, then it should be safe to allow the get.
Further reading from my Wrox ASP.NET MVC3 book
By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking. You do not want to return sensitive information using JSON in a GET request. For more details, see Phil's post at http://haacked.com/archive/2009/06/24/json-hijacking.aspx/ or this SO post.
Haack, Phil (2011). Professional ASP.NET MVC 3 (Wrox Programmer to Programmer) (Kindle Locations 6014-6020). Wrox. Kindle Edition.
Related StackOverflow question