Gho*_*ngi 34 ajax asp.net-mvc authorize
我使用jquery ajax函数提交表单.用户必须登录,否则他们必须重定向到登录页面.我已经使用了Authorize()属性.
[Authorize]
public ActionResult Creat()
{
....
}
Run Code Online (Sandbox Code Playgroud)
如果用户没有登录操作返回登录页面到jquery的ajax函数,它会显示在同一页面上,但我想将用户重定向到登录页面.有什么解决方案吗?
Ron*_*rby 87
工作示例:https://github.com/ronnieoverby/mvc-ajax-auth
重要部分:
AjaxAuthorizeAttribute:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
$(function () {
$(document).ajaxError(function (e, xhr) {
if (xhr.status == 403) {
var response = $.parseJSON(xhr.responseText);
window.location = response.LogOnUrl;
}
});
});
Run Code Online (Sandbox Code Playgroud)
在控制器中使用该属性:
[AjaxAuthorize]
public ActionResult Secret()
{
return PartialView();
}
Run Code Online (Sandbox Code Playgroud)
做一些ajax:
@Ajax.ActionLink("Get Secret", "Secret", new AjaxOptions { UpdateTargetId = "secretArea", })
<div id="secretArea"></div>
Run Code Online (Sandbox Code Playgroud)
只是#Ronnie答案的一个方便的补充
如果你想保持页面网址重定向.
var pathname = window.location.pathname;
if (xhr.status == 403) {
var response = $.parseJSON(xhr.responseText);
window.location = response.LogOnUrl + '?ReturnUrl=' + pathname;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20640 次 |
| 最近记录: |