我使用 jquery ajax 函数提交表单。用户必须登录,否则他们必须重定向到登录页面。我已经使用了 Authorize() 属性。
[Authorize]
public ActionResult Creat()
{
....
}
如果用户未登录,则操作将登录页面返回到 jquery 的 ajax 函数,并显示在同一页面上,但我想将用户重定向到登录页面。有什么解决办法吗?
我使用 jquery ajax 函数提交表单。用户必须登录,否则他们必须重定向到登录页面。我已经使用了 Authorize() 属性。
[Authorize]
public ActionResult Creat()
{
....
}
如果用户未登录,则操作将登录页面返回到 jquery 的 ajax 函数,并显示在同一页面上,但我想将用户重定向到登录页面。有什么解决办法吗?
工作示例:https ://github.com/ronnieoverby/mvc-ajax-auth
重要部分:
AjaxAuthorize 属性:
using System.Web.Mvc;
namespace MvcApplication1
{
public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAjaxRequest())
{
var urlHelper = new UrlHelper(context.RequestContext);
context.HttpContext.Response.StatusCode = 403;
context.Result = new JsonResult
{
Data = new
{
Error = "NotAuthorized",
LogOnUrl = urlHelper.Action("LogOn", "Account")
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
base.HandleUnauthorizedRequest(context);
}
}
}
}
Javascript:
$(function () {
$(document).ajaxError(function (e, xhr) {
if (xhr.status == 403) {
var response = $.parseJSON(xhr.responseText);
window.location = response.LogOnUrl;
}
});
});
在控制器中使用属性:
[AjaxAuthorize]
public ActionResult Secret()
{
return PartialView();
}
做一些ajax:
@Ajax.ActionLink("Get Secret", "Secret", new AjaxOptions { UpdateTargetId = "secretArea", })
<div id="secretArea"></div>
只是#Ronnie 答案的一个方便补充
如果您想将页面网址保留在重定向上。
var pathname = window.location.pathname;
if (xhr.status == 403) {
var response = $.parseJSON(xhr.responseText);
window.location = response.LogOnUrl + '?ReturnUrl=' + pathname;
}
作为 Ronnie Overby 回答的另一个扩展。
他的解决方案不适用于 webapi,但这很好,因为您可以使用普通的 Authorize 属性,然后在 ajaxError 函数中处理 401 状态,如下所示。
$(document).ajaxError(function (e, xhr) {
//ajax error event handler that looks for either a 401 (regular authorized) or 403 (AjaxAuthorized custom actionfilter).
if (xhr.status == 403 ||xhr.status == 401) {
//code here
}
});