您好,我正在尝试创建一个自定义授权过滤器,它允许我自动授权来自本地主机的请求(将用于我的测试)。
我发现了以下适用于 Asp.net 的内容,但是在将其移植到 asp.net core 时遇到了问题。
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);
}
}
如何将其移植到 asp.net core?
最佳答案
您可以创建一个中间件,在其中可以自动授权来自本地主机的请求。
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);
}
}
然后创建一个扩展方法
public static class CustomMiddleware
{
public static IApplicationBuilder UseMyAuthorize(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyAuthorize>();
}
}
最后将其添加到启动Configure
方法中。
app.UseMyAuthorize();
Asp.Net Core 没有 IsLoopback
属性。这是解决此问题的方法
https://stackoverflow.com/a/41242493/2337983
您还可以阅读有关 Middleware 的更多信息这里
关于asp.net - 使用 aspnet core 自定义授权过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41293420/