简体   繁体   English

检查当前页面是否需要授权

[英]Check if authorization is needed on current page

In web.config we can set authorization option individually for locations: web.config我们可以为位置分别设置授权选项:

<location path="request.ashx">
      <system.web>
          <authorization>
              <allow users="*" />
          </authorization>
      </system.web>
  </location>

How to get this option from code? 如何从代码中获取此选项?

Better than using Authorize attribute, i think that using an if condition would be far better. 比使用Authorize属性更好,我认为使用if条件会更好。

If(User.Identity.IsAuthenticated)
{
    If(User.Identity.IsInRole=="admin")
    {
        return view("Secret");
    }
    else
    {
            return view("NotAllowed")
    }
}
else
{
    return View("NeedAuth");
}

If user is suddenly redirected to loginpage as in attribute, he may think it as an error in website, but this way you would be able to clearly tell the user that he needs to Authenticate. 如果用户突然被重定向到属性中的登录页面,他可能会认为这是网站中的错误,但是通过这种方式,您将能够清楚地告诉用户他需要进行身份验证。

Try This : 尝试这个 :

public void ProcessRequest(HttpContext context)
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated == false)
        {
            context.Response.Redirect("Your Path");
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM