MVC JsonResult with [Authorize] attribute for login but not displaying view

I see strange behavior with MVC 3 methods that return JsonResult when used with the Authorize attribute. What looks like this is the authorization is correctly evaluated when I am not logged in, but instead of being redirected to the login form, the Json response is the login form. Is there an add attribute that directs the response so that it does not return a value, but instead redirects the user to the login form, preferably with the correct returnUrl value? What I did as a demo was set up a new MVC3 site and add the AspNetMembership to my DB using the aspnet_regsql.exe command. This all sets up and logs me correctly. The JsonResult behavior doesn't seem to be correct and I hope I just left out the attribute to make it work correctly. Any help is appreciated,thanks in advance.

Here is the account controller (excluding the Post action, which is not part of this question).

public class AccountController : Controller
    public ActionResult LogOn()
        return View();

    public JsonResult AuthorizedAction()
        return Json("Only returns if I am authorized");


Here is the Html markup:

<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#btnTest").click(function () {
                type: "POST",
                url: "Account/AuthorizedAction",
                data: {},
                success: function (result) {
                error: function (result) {
                    $("#testMe").html('Something broke in the ajax request');

<input type="button" id="btnTest" value="Test me" />
<div id="testMe">I have initial text</div>



1) When logged in, I get "Only return if I am authorized" in my test div 2) When not logged in and I have a breakpoint in my Logon () method, I see this value Request ["ReturnUrl"] " / Account / AuthorizedAction "

In the test div I have a login form displayed :) it looks like I just am not handling this correctly.


source to share

2 answers

You can take a look at the following blog post where Phil Haack explains a very good technique for detecting that a request for an unauthenticated resource has been made and acting accordingly by capturing the 401 HTTP status code.



try and return a partial view instead



All Articles