在ASP.NET MVC5中,您可以抛出一个带有HTTP代码的HttpException,这将设置如下所示的响应:
throw new HttpException((int)HttpStatusCode.BadRequest, "Bad Request.");
ASP.NET核心中不存在HttpException
。等价代码是什么?
我实现了自己的HttpException
和支持中间件,该中间件捕获所有HttpException
并将它们转换为相应的错误响应。下面可以看到一个简短的摘录。还可以使用boxed.aspnetcore Nuget包。
public void Configure(IApplicationBuilder application)
{
application.UseIISPlatformHandler();
application.UseStatusCodePagesWithReExecute("/error/{0}");
application.UseHttpException();
application.UseMvc();
}
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseHttpException(this IApplicationBuilder application)
{
return application.UseMiddleware<HttpExceptionMiddleware>();
}
}
internal class HttpExceptionMiddleware
{
private readonly RequestDelegate next;
public HttpExceptionMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await this.next.Invoke(context);
}
catch (HttpException httpException)
{
context.Response.StatusCode = httpException.StatusCode;
var responseFeature = context.Features.Get<IHttpResponseFeature>();
responseFeature.ReasonPhrase = httpException.Message;
}
}
}
public class HttpException : Exception
{
private readonly int httpStatusCode;
public HttpException(int httpStatusCode)
{
this.httpStatusCode = httpStatusCode;
}
public HttpException(HttpStatusCode httpStatusCode)
{
this.httpStatusCode = (int)httpStatusCode;
}
public HttpException(int httpStatusCode, string message) : base(message)
{
this.httpStatusCode = httpStatusCode;
}
public HttpException(HttpStatusCode httpStatusCode, string message) : base(message)
{
this.httpStatusCode = (int)httpStatusCode;
}
public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner)
{
this.httpStatusCode = httpStatusCode;
}
public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner)
{
this.httpStatusCode = (int)httpStatusCode;
}
public int StatusCode { get { return this.httpStatusCode; } }
}
从长远来看,我建议不要使用异常来返回错误。异常比仅仅从一个方法返回一个错误要慢。
.NET核心和ASP.NET核心到底有什么区别?
我正在使用ASP.NET内核。我正在创建一个基本的WebAPI。我想在出现问题时显示一个JSON错误。 打印屏幕在我的屏幕上显示want I want。唯一的问题是它的发送状态码为200。 我可以通过这样做来解决问题: 真诚的,布莱希特
也许我错过了它,但我正在试图弄清楚如何在ASP.NET核心中实现这一点。我查看了源代码(https://github.com/aspnet/security),但没有看到任何类似的内容。有没有新的方法来完成这一点?我需要创建一个控制器然后自己做吗? 我看到了如何通过中间件来设置OAuth身份验证,但这涉及到从API发出声明的授权部分。
如何在ASP.NET Core2.1项目中设置swagger属性?根据这篇文章,我应该使用,但我在swashbuckle.aspnetcore库中找不到它。还有 而且我找不到任何用于大摇大摆生成目的的实现。
我的大多数服务通常与crud方法相同