我正在尝试显示使用 Web API 时返回的相关错误消息HttpClient.PostJsonAsync<T>()
。
在我的 Web API 中,例如,在登录失败时,我会返回一个 401 未经授权的异常,其中包含正文中的消息,其中包含错误处理中间件;
public class HttpErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public HttpErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (HttpStatusCodeException exception)
{
if (!context.Response.HasStarted)
{
context.Response.StatusCode = (int)exception.StatusCode;
context.Response.Headers.Clear();
await context.Response.WriteAsync(exception.Message);
}
}
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class HttpErrorHandlerMiddlewareExtensions
{
public static IApplicationBuilder UseHttpErrorHandlerMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HttpErrorHandlerMiddleware>();
}
}
然后在邮递员中,这将显示消息,例如"无效的用户名或密码","用户被锁定"等。
但是,当我尝试在客户端捕获错误时,例如
try
{
var result = await _httpClient.PostJsonAsync<LoginResponse>("api/login", loginModel);
/* Removed for brevity */
}
catch(Exception ex)
{
return new LoginResponse { Success = false, Error = ex.Message };
}
返回的错误始终为"响应状态代码不指示成功:401(未经授权("。
请问我如何从PostJsonAsync<T>
的返回中获取错误的详细信息?
401
是一个验证响应,它不会在HttpErrorHandlerMiddleware
中捕获。
我不确定您如何实现 401 和PostJsonAsync
.这是为您提供的工作演示:
控制器操作
[HttpPost] public IActionResult Login(LoginModel loginModel) { return StatusCode(401, new LoginResponse { Success = false, Error = "Invalid User Name and Password" }); }
HttpClient Request
public async Task<LoginResponse> Test(LoginModel loginModel) { var _httpClient = new HttpClient(); var result = await _httpClient.PostAsJsonAsync<LoginModel>("https://localhost:44322/api/values/login", loginModel); return await result.Content.ReadAsAsync<LoginResponse>(); }