我在考虑如何使用自定义属性正确保护JsonResult操作,而不是在每个操作上执行此类操作,例如在此处ASP.NET MVC JsonResult and AuthorizeAttribute
if (!User.Identity.IsAuthenticated)
return Json("Need to login");
但问题是如何创建这样的属性才能返回Json。 所以我从那开始:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class JsonAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
//?
}
//Need to return json somehow ?
}
}
我如何从这样的属性返回json结果?任何想法?
答案 0 :(得分:3)
您可以使用ActionFilterAttribute
,无需使用httpcontext.response.write
或其他任何内容即可返回结果。
public class JsonActionFilterAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if (!HttpContext.Current.User.Identity.IsAuthenticated) {
filterContext.Result = new JsonResult() { Data = "Need to login." };
}
base.OnActionExecuting(filterContext);
}
}
答案 1 :(得分:3)
1种方法是覆盖AuthorizeAttribute.HandleUnauthorizedRequest
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
throw new CustomUnauthorizedException();
}
...然后在你的Global.asax中:
protected void Application_Error(object sender, EventArgs e)
{
Exception error = Server.GetLastError();
if (error is CustomUnauthorizedException) {
if (AjaxRequest(Request)) {
... return Json response.
} else {
... redirect
}
}
}
因此,您可以在代码库中的任何位置抛出异常,并在Global.asax中集中处理该异常
答案 2 :(得分:0)
尝试一下..它对我有用
res.set({
"Access-Control-Allow-Origin", "*",
"Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"
});