How to detect and reject a non-JavaScript post to MVC controller
Is there a simple way I can detect and reject a non-JavaScript post to an MVC Controller?
Say I have some JavaScript that submits the form via Ajax:
function SubmitForm()
{
var data = $("form").serialize();
$.post("/MyController/MyAction/", data, fun开发者_JS百科ction(data, response){
//Process response
});
return false;
}
If the user disables JavaScript the form will still post to the controller via a standard form post. I understand that I can't stop it posting but can I detect and reject a non-JavaScript post from the controller and send the user to an error page?
I also understand that this is probably not something that is a standard part of the Controller's functionality so I am wondering if anyone has come up with a trick for achieving this.
if (!Request.IsAjaxRequest) return RedirectToAction("YourForbiddenAction");
You could use JavaScript to add a specific hidden input to the form:
$('#your_form').append('<input type="hidden" name="got_js" value="1"/>');
And then, on the server you can check if there is a got_js
parameter coming in. If there isn't then you're probably dealing with someone or something that doesn't have JavaScript support. You could do the same thing inside your SubmitForm
function by adding something else to data
:
var data = $("form").serialize();
data = data ? data + '&got_js=1' : 'got_js=1';
How about setting the form method to "get"? You can then easily detect the method on the server side and only process when the method is post.
<form method="get">
...
</form>
Edit: Checked the serialize() function docs and it doesn't actually require that your inputs be inside a form. As long as you have a way to select them, such as an enclosing div. So that's an option as well.
In your controller check for the headers that jquery sends with ajax requests.
if($_SERVER['HTTP_X_REQUESTED_WITH'] !='XMLHttpRequest'){
die();
}
Edit: just realized that you are not using PHP but asp.net. You should be able to do that same thing though.
Added by balexandre
if( Request.ServerVariables["HTTP_X_REQUESTED_WITH"].ToLower() != "xmlhttprequest" )
return RedirectToAction("Failed");
but in .NET there is a better way:
if( !Request.IsAjaxRequest )
return RedirectToAction("Failed");
You should use an ActionFilter on your controller action.
[AjaxOnly] public ActionResult AjaxActionMethod() { .... }
This is not out of the box so you will need to write your own. You can find a good example here
精彩评论