我如何编写自定义属性的函数做一些事情,并在asp.netnet mvc 5 c中重定向#
问题描述:
我想写我自己的授权属性(如[授权],但不是在asp .net身份)以检查db和if用户没有授权将他重定向到某个地方。谁能帮忙?我如何编写自定义属性的函数做一些事情,并在asp.netnet mvc 5 c中重定向#
答
是的,你可以创建你customAuthorize attribut,为此,你可以从asp.net类继承AuthorizeAttribute,让你像attribut -
(我在我的项目中使用这个)
public class CustomAuthorize : AuthorizeAttribute
{
private User_MasterEntities db = new User_MasterEntities();
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Restricted" }));//new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authenticated
return false;
}
string user = HttpContext.Current.User.Identity.Name;
bool isAdmin = IsAppUser(user);
return isAdmin;
}
和IsAppUser是你的函数,它返回它是管理员或不从数据库
[多少研究工作预计堆栈溢出用户?](https://meta.stackoverflow.com/a/261593/3082296) – adiga
[我downvoted因为这个问题没有证据研究努力](http://idownvotedbecau.se/noresearch/),并且因为它[不是真正的问题](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-帮助 - 我 - 不 - 的 - 实际问题)。请参阅:[为什么“有人可以帮助我?”不是真正的问题?](http://meta.stackoverflow.com/q/284236) – EJoshuaS