在以前的ASP.NET Core 2.0 Web API中,如果用户未经身份验证或未经授权而无法访问该操作,则能够返回自定义模型。但是,此方法在新的ASP.NET Core 2.1中不再起作用。
我没有得到我的自定义模型,而是得到
401 Unauthorized
和403 Forbidden
我的中间件
public class UserAuthenticationMiddleware
{
private readonly RequestDelegate next;
public UserAuthenticationMiddleware(RequestDelegate _next)
{
next = _next;
}
public async Task Invoke(HttpContext context)
{
if (context.Response.StatusCode == 401)
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new ApiErrorResponse(System.Net.HttpStatusCode.Unauthorized, "Please log in.")));
return;
}
else if (context.Response.StatusCode == 403)
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new ApiErrorResponse(System.Net.HttpStatusCode.Forbidden, "You are not authorized to access this resource.")));
return;
}
await next.Invoke(context);
}
}
Startup.cs
app.UseMiddleware<UserAuthenticationMiddleware>();