How is the common class AuthorizeAttribute defined in .NET?

In .NET, you can create custom authorization attributes by inheriting from the AuthorizeAttribute class. AuthorizeAttribute is an abstract base class used to mark controllers or action methods in ASP.NET that require authorized access.

To create a generic AuthorizeAttribute class, you can define it by following the steps below:

  1. Attribute that grants permission
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
   // 程序逻辑将在这里添加
}
  1. Check for authorization
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
   // 实现授权逻辑
   return ...; // 返回true表示允许访问,返回false表示拒绝访问
}
  1. ManageUnauthorizedRequest
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
   // 处理未经授权的请求
   // 可以进行重定向或返回特定的HTTP状态码
}

By customizing the AuthorizeAttribute class, you can use this attribute on controllers or action methods to implement permission control. For example:

[CustomAuthorize]
public ActionResult Index()
{
   // 控制器逻辑
   return View();
}

The above steps outline the basic process of defining a general AuthorizeAttribute class. Depending on specific requirements, relevant authorization logic and handling operations can be added to the AuthorizeCore and HandleUnauthorizedRequest methods.

bannerAds