问题描述
在 ASP.NET MVC 5 中,您可以抛出 HttpException 带有 HTTP 代码,这将设置响应如下:
In ASP.NET MVC 5 you could throw a HttpException with a HTTP code and this would set the response like so:
HttpException
在 ASP.NET Core 中不存在.什么是等效代码?
HttpException
does not exist in ASP.NET Core. What is the equivalent code?
推荐答案
我实现了自己的 HttpException
并支持中间件,它可以捕获所有 HttpException
并将它们转换为相应的错误响应.下面可以看到一个简短的摘录.您还可以使用 Boxed.AspNetCore Nuget 包.
I implemented my own HttpException
and supporting middleware which catches all HttpException
's and turns them into the corresponding error response. A short extract can be seen below. You can also use the Boxed.AspNetCore Nuget package.
扩展方法
中间件
HttpException
从长远来看,我建议不要使用异常来返回错误.异常比仅从方法返回错误要慢.
In the long term, I would advise against using exceptions for returning errors. Exceptions are slower than just returning an error from a method.
这篇关于ASP.NET Core 等效于 ASP.NET MVC 5 的 HttpException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!