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 allowingHTTP 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
Related StackOverflow question
With most recents browsers (starting with Firefox 21, Chrome 27, or IE 10), this is no more a vulnerability.
To make it easier for yourself you could also create an actionfilterattribute
and use it on your action
You do not need it.
If your action has the
HttpPost
attribute, then you do not need to bother with setting theJsonRequestBehavior
and use the overload without it. There is an overload for each method without theJsonRequestBehavior
enum. Here they are:Without JsonRequestBehavior
With JsonRequestBehavior
Improving upon the answer of @Arjen de Mooij a bit by making the AllowJsonGetAttribute applicable to mvc-controllers (not just individual action-methods):
By default Jsonresult "Deny get"
Suppose if we have method like below
By default it "Deny Get".
In the below method
When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.