在以前的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>();