How do I get [authorize] work the way I want?

I have this link

@Ajax.ActionLink("comment", "CreateDebateComment", new { id = Model.DebateID}, new AjaxOptions
{
    UpdateTargetId = "comment-entry-box",
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "GET"
});

      

What is calling this controller

  [Authorize]
    public PartialViewResult CreateDebateComment(int id)
    {


            DebateIDForComment = id;
            return PartialView("_CreateDebateCommentPartial");

    }

      

If the user is not logged in, it is redirected to the LogOn page, but loaded into the comment-entry-box div instead of being redirected to the login page

I also tried this variation

 public PartialViewResult CreateDebateComment(int id)
    {
        if (!User.Identity.IsAuthenticated)
        {
            RedirectToAction("LogOn", "Account");
        }

            DebateIDForComment = id;
            return PartialView("_CreateDebateCommentPartial");

    }

      

But it does not redirect and will still load the partialView

Does anyone know how I can get this to function the way I want? I need the login page to load as usual and not in the comment input field.

+3


source to share


2 answers


You can take a look at a blog post where Phil Haack explains how you can suppress the forms authentication module from redirecting to LogOn if the request was an AJAX request and returns a 401 HTTP status code that can be intercepted by the client and redirected accordingly.

So add the HttpModule it showed or installed its NuGet package to your project and then all you have to do is register a global ajax event that will be triggered every time some of your AJAX requests on the page hit 401 from server:



<script type="text/javascript">
    $.ajaxSetup({
        statusCode: {
            401: function () {
                window.location.href = '@Url.Action("logon", "account")';
            }
        }
    });
</script>

      

+1


source


What if, instead of using [Authorize] (which I understand, this is a question) you check authorization in the code (for example !User.Identity.IsAuthenticated

) and you complete the response in json, and false

on the client side redirects to the login [via javascript]

True

followed by the data you want to display

t



{ "Success": "false" }

      

or

{ "Success": "true", "data": "blah blah blah" }

      

+1


source







All Articles