Reputation: 3512
I have this link
@Ajax.ActionLink("comment", "CreateDebateComment", new { id = Model.DebateID}, new AjaxOptions
{
UpdateTargetId = "comment-entry-box",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
});
Which triggers this controller
[Authorize]
public PartialViewResult CreateDebateComment(int id)
{
DebateIDForComment = id;
return PartialView("_CreateDebateCommentPartial");
}
If the user is not logged in they get redirected to the LogOn page but it loads in the comment-entry-box div instead of redirecting 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 as I want ? I need the Log On page to load as normal and not in the comment-entry-box.
Upvotes: 3
Views: 278
Reputation: 1038810
You may take a look at the following blog post in which Phil Haack explains how you could suppress the forms authentication module from redirecting to the LogOn page if the the request was an AJAX request and return a 401 HTTP status code which could be intercepted by the client and redirect accordingly.
So either add the HttpModule he showed or install his NuGet package to your project and then all you have to do is to register a global ajax event that will be trigerred every time some of your AJAX requests on the page hits a 401 from the server:
<script type="text/javascript">
$.ajaxSetup({
statusCode: {
401: function () {
window.location.href = '@Url.Action("logon", "account")';
}
}
});
</script>
Upvotes: 1
Reputation: 2758
What if instead of using [Authorize] (which I realize IS the question)
You check authorization in code (eg !User.Identity.IsAuthenticated
) and you wrap your response in json, a false
on the client side redirects to the login [via javascript]
True
is followed by the data you want to display
ie
{ "Success": "false" }
or
{ "Success": "true", "data": "blah blah blah" }
Upvotes: 1