我在想如何正確安全JsonResult動作與自定義屬性而不是做那種這對每個動作就像在說這裏ASP.NET MVC JsonResult and AuthorizeAttribute如何創建自定義的JsonAuthorize屬性來保護返回JsonResults的操作?
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結果?有任何想法嗎?