我不知道为什么我的API会为未经授权的调用返回OK状态消息。这是我的启动配置方法
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger(options => options.RouteTemplate = _swaggerConfigurations.JsonRoute);
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint(_swaggerConfigurations.UiEndPoint, _swaggerConfigurations.Name);
});
}
else
{
app.UseExceptionHandler(builder =>{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message);
}
});
});
}
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
控制器动作方法:
[HttpPost(ApiRoutes.Auth.Login)]
public async Task<IActionResult> Login(UserToLoginDto dto)
{
var loggedInResult = await _authService.Login(dto);
if (loggedInResult == null)
return Unauthorized();
return Ok(loggedInResult);
}
请让我知道我在做什么错。
经过一些详细的代码审查,我发现我尚未将AddCors()添加到我的服务中,但是我正在管道中直接使用它,也正在使用UseHttpsRedirection中间件。我的Angular应用正在开发模式下运行,没有SSL。 API和客户端都在没有任何证书的情况下运行。添加AddCors()并删除UseHttpsRedirection中间件后,将收到正确的HttpErrorResponse。