【问题标题】:Why does Result return the correct status code only in the response body?为什么 Result 只在响应正文中返回正确的状态码?
【发布时间】:2022-10-24 11:08:57
【问题描述】:

每当我返回任何 Result 时,它总是 200 状态码。例如检查此代码

public async Task<IResult> Login(UserLoginDto login)
{
    var user = await _userMgr.FindByEmailAsync(login.Email);
    if (user != null)
    {
        var result = await _signinManager.PasswordSignInAsync(user, login.Password, false, false);

        if (result.Succeeded)
        {
            var token = await _authRepo.GenerateToken(user);
            _logger.LogInformation("User with email: {Email} is logged in ", user.Email);
            return Results.Ok(new { user.Email,  Token = token });
        }
        else
        {
            return Results.Unauthorized();
        }
    }
    return Results.NotFound();
}

始终仅在响应正文中返回正确的状态代码,并在响应标头中返回 200Ok。我该如何解决这种奇怪的行为?我查看了 .net 6 文档,但无济于事。

更新#1

这是中间件

var app = builder.Build();
await app.SystemInit(builder.Configuration);

app.UseSwagger();
app.UseSwaggerUI();

// Configure the HTTP request pipeline.
//todo: disable cors for production env
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseCors(myAllowSpecificOrigins);

}

app.UseHealthChecks("/api/healthy");

// app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

【问题讨论】:

  • 强烈建议某些东西正在使用 IResult 并不恰当地包装它。可能是一些配置错误/编写错误的中间件、某种代理等。
  • 你是对的。但中间是样板。我将在我的帖子中添加我的中间人
  • @Ryan 为什么不使用 return NotFound();
  • 嗨,欢迎。微软有很好的文档。请阅读:link
  • 通过放置断点检查结果中返回的值是什么?

标签: c# asp.net-core .net-6.0


【解决方案1】:

所有结果方法在 MVC 操作中返回 200 的原因是它用于最小 api 而不是 MVC 操作方法。

result.notfound method 将构建一个 notfound.cs 对象,这个 notfound.cs 对象包含一个用于构建 httpresponse 的 executeasync 方法。

由于您只是返回 Result 而不是使用 ExecuteAsync 方法,因此它只会将 json 对象返回给客户端,而不是调用 ExecuteAsync 方法来编写新的响应。

在 MVC 操作方法中返回状态代码的正确方法应该使用 IActionResult Not Found() 方法。

如果你使用最小的 API,你可以像这样使用 iresult:

app.MapGet("/weatherforecast", () => Results.NotFound());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多