[英]return a 404 status code and get no contents in response
当我的 StatusCode 为 404 时,我抛出了我的自定义异常,浏览器得到 200 并且没有内容,但使用其他 StatusCode 一切正常
如何解决此问题并在我的回复中获得 404 而不是 200
这是我的中间件
public static class ExceptionHandlingMiddlewareExtensions
{
public static IApplicationBuilder UseNativeGlobalExceptionHandler(this IApplicationBuilder app)
{
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
try
{
var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
var exception = errorFeature.Error;
// Log exception and/or run some other necessary code...
var errorResponse = new ErrorResponse();
if (exception is HttpException httpException)
{
errorResponse.StatusCode = httpException.StatusCode;
errorResponse.Message = httpException.Message;
}
context.Response.StatusCode = (int) errorResponse.StatusCode;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(errorResponse.ToJsonString());
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
});
});
return app;
}
}
}
这是我的控制器,我在这里抛出 404 StatusCode enter image description here
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
throw new HttpException(HttpStatusCode.NotFound, "Not found");
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
尝试从ControllerBase
类返回未找到的方法。
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return NotFound();
}
扩展您的控制器以使用基类。 它应该是这样的:
public class WeatherForecastController : ControllerBase
{
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.