开发者

Returning Json as an ActionResult won't let the exception message through

So I have a link on my page that is causing some code to break. The code throws an Exception, which causes my code to jump to the "Catch" block on my controller. The catch block looks as follows:

catch (Exception e)
{
    return Json(e.ToString());
}

What happens is, I see this error on the front end:

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

Now if I change the behavior of that above return statement to the following:

return Json(e.ToString(), JsonRequestBehavior.AllowGet);

On the front end, I actually get a pop-up dialogue asking me if I want to download a Json item from localh开发者_如何学Goost, and I don't get just a more descriptive error.

What is going on here and how do I fix it?


An action which returns JSON needs to be invoked using AJAX. If you simply put a link in your page pointing to this action because the server returns JSON the browser doesn't know what to do with it. So for example if you are using jquery you could use the $.getJSON() method to call this action:

$(function() {
    $.getJSON('<%= Url.Action("SomeAction") %>', { }, function(result) {
        // do something with the result
        alert(result);
    });
});

There are two other cases I can think of when the scenario you are describing could occur:

  • You have AJAXified a link pointing to this controller action but you have a javascript error and the browser simply follows the link sending a GET request
  • You have AJAXified a link pointing to this controller action but you forgot to cancel the default action by returning false from your .click() callback and the browser simply follows the link sending a GET request
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜