使用aspnet核心自定义授权过滤器

Jam*_*sla 7 asp.net asp.net-mvc asp.net-core-mvc asp.net-core

嗨,我正在尝试创建一个自定义授权过滤器,允许我自动授权来自localhost的请求(将用于我的测试).

我为Asp.net找到了以下一个但是在将它移植到asp.net核心时遇到了麻烦.

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Request.Url.IsLoopback)
        {
            // It was a local request => authorize the guy
            return true;
        }

        return base.AuthorizeCore(httpContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何将其移植到asp.net核心?

Ahm*_*mar 11

您可以创建一个中间件,您可以在其中自动授权来自localhost的请求.

public class MyAuthorize
{
   private readonly RequestDelegate _next;
   public MyAuthorize(RequestDelegate next)
   {
      _next = next;
   }

   public async Task Invoke(HttpContext httpContext)
   {
     // authorize request source here.

    await _next(httpContext);
   }
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个扩展方法

public static class CustomMiddleware
{
        public static IApplicationBuilder UseMyAuthorize(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyAuthorize>();
        }
}
Run Code Online (Sandbox Code Playgroud)

最后在启动Configure方法中添加它.

app.UseMyAuthorize();
Run Code Online (Sandbox Code Playgroud)

Asp.Net Core没有IsLoopback财产.这是 /sf/answers/2886974541/的解决方法

您还可以在此处阅读有关中间件的更多信息