.net-core中间件返回空白结果

Sve*_*art 17 c# middleware asp.net-core

我正在使用API​​制作网站,API需要验证,因此用户只能获取自己的数据.我编写了以下中间件来验证登录.

public class ApiAuthenticationMiddleware
{
    private readonly RequestDelegate _next;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

    public ApiAuthenticationMiddleware(RequestDelegate next,
        SignInManager<ApplicationUser> signInManager,
        UserManager<ApplicationUser> usermanager)
    {
        _next = next;
        _signInManager = signInManager;
        _userManager = usermanager;
    }

    public async  Task Invoke(HttpContext context)
    {
        if (!context.Request.Query.ContainsKey("password") || !context.Request.Query.ContainsKey("email"))
        {
            context.Response.StatusCode = 401; //UnAuthorized
            await context.Response.WriteAsync("Invalid User Key");
            return;
        }
        var email = context.Request.Query["email"];
        var password = context.Request.Query["password"];

        var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false);
        if (result.Succeeded)
        {
            await _next.Invoke(context);
        }
        else if (//some more checks)
            context.Response.StatusCode = 401; //UnAuthorized
            await context.Response.WriteAsync("Invalid User Key");
            return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要的是,如果用户没有有效登录,则会显示空白页或"无效用户密钥"之类的错误消息.然而,目前发生的是返回主页(因为我的中间件在usemvc之前调用,而return语句跳过usemvc完成的控制器请求).

我在startup.cs中的configure方法中的相关代码

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

        app.UseIdentity();
        app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)),
            builder =>
            {
                builder.UseMiddleware<ApiAuthenticationMiddleware>();
            });
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
Run Code Online (Sandbox Code Playgroud)

如何让我的中间件返回带有状态代码的空白页?

请解释downvoting的原因,以便我可以改进问题并知道我做错了什么.

更新

在尝试了很多东西后,我发现当我删除时:

 context.Response.StatusCode = 401; //UnAuthorized
Run Code Online (Sandbox Code Playgroud)

它按预期工作,用户获取以下内容给出的消息:

await context.Response.WriteAsync("Invalid User Key"); 
Run Code Online (Sandbox Code Playgroud)

Howerver我不希望用户在登录失败时获得200状态代码但是401状态代码.但是当使用状态代码行时,用户被重定向.那么如何在没有重定向的情况下发送状态码呢?

Dar*_*tar 10

在设置 StatusCode 之前尝试使用 .Clear() 。

            context.Response.Clear();
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            await context.Response.WriteAsync("Unauthorized");
Run Code Online (Sandbox Code Playgroud)


Bra*_*don 6

我有一种预感,app.UseIdentity()默认行为是当 403/401 发生时,它将拦截响应并启动重定向。尝试将其注释掉,看看是否有效。

替代解决方案请参阅:/sf/answers/3041930601/

最后评论:我强烈建议不要为每个请求传递凭据。我建议使用预构建的身份验证提供程序并作为中间件实施。该Authorize属性应该足以满足所发出的请求,并且可以执行您正在寻找的操作。如果您确实想返回一些特殊的内容,您可以使用中间件覆盖响应,就像app.UseIdentity()中间件可能通过重定向一样。