Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .net核心中间件返回空白结果_C#_Asp.net Core_Middleware - Fatal编程技术网

C# .net核心中间件返回空白结果

C# .net核心中间件返回空白结果,c#,asp.net-core,middleware,C#,Asp.net Core,Middleware,我正在制作一个带有API的网站,API需要验证,所以用户只能获得自己的数据。我编写了以下中间件来验证登录 public class ApiAuthenticationMiddleware { private readonly RequestDelegate _next; private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<Ap

我正在制作一个带有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;
        }
    }
}
它按预期工作,用户获得以下信息:

await context.Response.WriteAsync("Invalid User Key"); 

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

我有一种预感,
app.UseIdentity()
具有默认行为,即当403/401发生时,它将拦截响应并启动重定向。试着评论一下,看看是否有效

替代解决方案见:

最后一点意见:我强烈建议不要为每个请求传递凭据。我建议使用预构建的身份验证提供程序并将其实现为您的中间件。
Authorize
属性应该足以满足请求,并且可以完成您正在寻找的任务。如果您确实想返回一些特殊的内容,可以使用中间件覆盖响应,例如
app.UseIdentity()
中间件可能带有重定向。

在设置状态码之前,尝试使用.Clear()

            context.Response.Clear();
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            await context.Response.WriteAsync("Unauthorized");

您还应该设置ContentType。 大概是这样的:

        context.Response.ContentType = "text/plain";
        context.Response.StatusCode = 401; //UnAuthorized
        await context.Response.WriteAsync("Invalid User Key");

为什么不使用
Authorize
attributeAuthorize假设用户已登录(如果im正确,则通过cookie)im为移动应用程序制作API,以便应用程序发送需要来自有效用户的请求。如果不是loggedin,那么authorize将重定向到register页面,这不是我想要的API行为。该中间件与Authorize一起工作Attribute@ChristianSauer谢谢Christian,我会的,但我仍然想知道如何解决当前的问题。在每个请求中传递凭据听起来不是个好主意。我不是专家,但应该使用cookie身份验证或类似OAuth2的东西,其中传递的是一个短期密钥。您是否尝试过在响应对象中设置
ContentType
标题?
            context.Response.Clear();
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            await context.Response.WriteAsync("Unauthorized");
        context.Response.ContentType = "text/plain";
        context.Response.StatusCode = 401; //UnAuthorized
        await context.Response.WriteAsync("Invalid User Key");