【发布时间】:2019-03-08 19:09:10
【问题描述】:
我决定为 ASP.NET API core 2.1 制作一个自定义中间件。
public class AuthorizeMiddleware
{
private readonly RequestDelegate _next;
private readonly AuthorizeOptions _options;
public AuthorizeMiddleware(RequestDelegate next, AuthorizeOptions options)
{
_next = next;
_options = options;
}
public async Task Invoke(HttpContext context)
{
bool hasRole = false;
if (hasRole)
{
await context.Response.WriteAsync($"Not authorized, you need role: {_options.Role}");
}
else
{
await _next.Invoke(context);
}
}
}
public struct AuthorizeOptions
{
public AuthorizeOptions(string role)
{
Role = role;
}
public string Role { get; set; }
}
当我尝试在我的 Application.cs 中使用这个中间件时
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
app.UseHttpsRedirection();
}
app.UseRouter(AuthenticatedRoutes(app));
app.UseMvc();
}
private IRouter AuthenticatedRoutes(IApplicationBuilder applicationBuilder)
{
IRouteBuilder builder = new RouteBuilder(applicationBuilder);
builder.MapMiddlewareGet("/api/values", appBuilder =>
{
appBuilder.UseMiddleware<AuthorizeMiddleware>(new AuthorizeOptions("User"));
appBuilder.UseMvc();
});
return builder.Build();
}
这工作得很好,但是当我删除 appBuilder.UseMvc();从 MapMiddlewareGet 和我的函数调用返回 404 的具体路线。
我尝试将 appRouter 放在 app.useMvc() 之上。如果没有成功,当调用 _next.Invoke() 时,我的中间件 next 函数仍然返回 404。
那么为什么每当我在 appBuilder 中调用 useMvc() 时它会起作用,我是否在做一些被认为是不好的做法,为什么我必须在 MapMiddlewareGet() 中使用 app.useMvc()?
【问题讨论】:
标签: asp.net-core-webapi asp.net-core-2.1 asp.net-core-middleware