ASP.NET 相当于 ASP.NET MVC 5 的 HttpException 的核心
ASP.NET Core equivalent of ASP.NET MVC 5's HttpException
在 ASP.NET MVC 5 中,您可以抛出带有 HTTP 代码的 HttpException,这将像这样设置响应:
throw new HttpException((int)HttpStatusCode.BadRequest, "Bad Request.");
HttpException
在 ASP.NET 核心中不存在。等效代码是什么?
经过brief chat with @davidfowl后,似乎ASP.NET5没有HttpException
或HttpResponseException
这样的概念"magically"转向响应消息。
您可以做的是 hook into the ASP.NET 5 pipeline via MiddleWare,并创建一个为您处理异常的程序。
这是他们的错误处理程序中间件 source code 中的一个示例,它会将响应状态代码设置为 500,以防管道进一步发生异常:
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
private readonly ErrorHandlerOptions _options;
private readonly ILogger _logger;
public ErrorHandlerMiddleware(RequestDelegate next,
ILoggerFactory loggerFactory,
ErrorHandlerOptions options)
{
_next = next;
_options = options;
_logger = loggerFactory.CreateLogger<ErrorHandlerMiddleware>();
if (_options.ErrorHandler == null)
{
_options.ErrorHandler = _next;
}
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError("An unhandled exception has occurred: " + ex.Message, ex);
if (context.Response.HasStarted)
{
_logger.LogWarning("The response has already started,
the error handler will not be executed.");
throw;
}
PathString originalPath = context.Request.Path;
if (_options.ErrorHandlingPath.HasValue)
{
context.Request.Path = _options.ErrorHandlingPath;
}
try
{
var errorHandlerFeature = new ErrorHandlerFeature()
{
Error = ex,
};
context.SetFeature<IErrorHandlerFeature>(errorHandlerFeature);
context.Response.StatusCode = 500;
context.Response.Headers.Clear();
await _options.ErrorHandler(context);
return;
}
catch (Exception ex2)
{
_logger.LogError("An exception was thrown attempting
to execute the error handler.", ex2);
}
finally
{
context.Request.Path = originalPath;
}
throw; // Re-throw the original if we couldn't handle it
}
}
}
你需要用StartUp.cs
注册它:
public class Startup
{
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerfactory)
{
app.UseMiddleWare<ExceptionHandlerMiddleware>();
}
}
或者,如果您只想 return 任意状态代码而不关心基于异常的方法,您可以使用
return new HttpStatusCodeResult(400);
更新:从 .NET Core RC 2 开始,Http 前缀被删除。现在是:
return new StatusCodeResult(400);
我实现了自己的 HttpException
和支持中间件,它捕获所有 HttpException
并将它们转换为相应的错误响应。下面是一个简短的摘录。您还可以使用 Boxed.AspNetCore Nuget 包。
Startup.cs
中的用法示例
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;
}
}
}
HttpException
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; } }
}
从长远来看,我建议不要使用异常来返回错误。异常比仅从方法返回错误要慢。
Microsoft.AspNet.Mvc.Controller
基础 class 公开了一个 HttpBadRequest(string)
重载,它将一条错误消息发送给 return 给客户端。因此,在控制器操作中,您可以调用:
return HttpBadRequest("Bad Request.");
最终我的鼻子认为从控制器操作中调用的任何私有方法都应该是完全 http 上下文感知和 return IActionResult
,或者执行一些其他完全独立于事实上,它在 http 管道内。当然这是我个人的意见,但是执行某些业务逻辑的 class 不应该 returning HTTP 状态代码,而应该抛出自己的异常,这些异常可以在controller/action级。
ASP.NET Core 本身没有等效项。正如其他人所说,实现这一点的方法是使用中间件和您自己的例外。
Opw.HttpExceptions.AspNetCore NuGet 包正是这样做的。
Middleware and extensions for returning exceptions over HTTP, e.g. as ASP.NET Core Problem Details. Problem Details are a machine-readable format for specifying errors in HTTP API responses based on https://www.rfc-editor.org/rfc/rfc7807. But you are not limited to returning exception results as Problem Details, but you can create your own mappers for your own custom formats.
它是可配置的并且有据可查。
这是开箱即用的例外列表:
4xx
- 400 BadRequestException
- 400 InvalidModelException
- 400 ValidationErrorException
- 400 InvalidFileException
- 401 未授权异常
- 403 禁止异常
- 404 NotFoundException
- 404 NotFoundException
- 409 冲突异常
- 409 ProtectedException
- 415 UnsupportedMediaTypeException
5xx
- 500 InternalServerErrorException
- 500 DbErrorException
- 500 序列化错误异常
- 503 服务不可用异常
从 ASP.NET Core 3 开始,您可以使用 ActionResult
到 return HTTP 状态代码:
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<ITEMS_TYPE> GetByItemId(int id)
{
...
if (result == null)
{
return NotFound();
}
return Ok(result);
}
这里有更多详细信息:https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1
这是@muhammad-rehan-saeed 回答的扩展版本。
它有条件地记录异常并禁用 http 缓存。
如果你使用这个和 UseDeveloperExceptionPage,你应该调用 UseDeveloperExceptionPage before this.
Startup.cs:
app.UseMiddleware<HttpExceptionMiddleware>();
HttpExceptionMiddleware.cs
/**
* Error handling: throw HTTPException(s) in business logic, generate correct response with correct httpStatusCode + short error messages.
* If the exception is a server error (status 5XX), this exception is logged.
*/
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 e)
{
var response = context.Response;
if (response.HasStarted)
{
throw;
}
int statusCode = (int) e.StatusCode;
if (statusCode >= 500 && statusCode <= 599)
{
logger.LogError(e, "Server exception");
}
response.Clear();
response.StatusCode = statusCode;
response.ContentType = "application/json; charset=utf-8";
response.Headers[HeaderNames.CacheControl] = "no-cache";
response.Headers[HeaderNames.Pragma] = "no-cache";
response.Headers[HeaderNames.Expires] = "-1";
response.Headers.Remove(HeaderNames.ETag);
var bodyObj = new {
Message = e.BaseMessage,
Status = e.StatusCode.ToString()
};
var body = JsonSerializer.Serialize(bodyObj);
await context.Response.WriteAsync(body);
}
}
}
HTTPException.cs
public class HttpException : Exception
{
public HttpStatusCode StatusCode { get; }
public HttpException(HttpStatusCode statusCode)
{
this.StatusCode = statusCode;
}
public HttpException(int httpStatusCode)
: this((HttpStatusCode) httpStatusCode)
{
}
public HttpException(HttpStatusCode statusCode, string message)
: base(message)
{
this.StatusCode = statusCode;
}
public HttpException(int httpStatusCode, string message)
: this((HttpStatusCode) httpStatusCode, message)
{
}
public HttpException(HttpStatusCode statusCode, string message, Exception inner)
: base(message, inner)
{
}
public HttpException(int httpStatusCode, string message, Exception inner)
: this((HttpStatusCode) httpStatusCode, message, inner)
{
}
}
我用这段代码得到的结果比用 :
- 使用异常处理程序:
- 自动记录每个“正常”异常(例如 404)。
- 在开发模式下禁用(当调用 app.UseDeveloperExceptionPage 时)
- 不能只捕获特定的异常
- Opw.HttpExceptions.AspNetCore:当一切正常时记录异常
另见
在 ASP.NET MVC 5 中,您可以抛出带有 HTTP 代码的 HttpException,这将像这样设置响应:
throw new HttpException((int)HttpStatusCode.BadRequest, "Bad Request.");
HttpException
在 ASP.NET 核心中不存在。等效代码是什么?
经过brief chat with @davidfowl后,似乎ASP.NET5没有HttpException
或HttpResponseException
这样的概念"magically"转向响应消息。
您可以做的是 hook into the ASP.NET 5 pipeline via MiddleWare,并创建一个为您处理异常的程序。
这是他们的错误处理程序中间件 source code 中的一个示例,它会将响应状态代码设置为 500,以防管道进一步发生异常:
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
private readonly ErrorHandlerOptions _options;
private readonly ILogger _logger;
public ErrorHandlerMiddleware(RequestDelegate next,
ILoggerFactory loggerFactory,
ErrorHandlerOptions options)
{
_next = next;
_options = options;
_logger = loggerFactory.CreateLogger<ErrorHandlerMiddleware>();
if (_options.ErrorHandler == null)
{
_options.ErrorHandler = _next;
}
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError("An unhandled exception has occurred: " + ex.Message, ex);
if (context.Response.HasStarted)
{
_logger.LogWarning("The response has already started,
the error handler will not be executed.");
throw;
}
PathString originalPath = context.Request.Path;
if (_options.ErrorHandlingPath.HasValue)
{
context.Request.Path = _options.ErrorHandlingPath;
}
try
{
var errorHandlerFeature = new ErrorHandlerFeature()
{
Error = ex,
};
context.SetFeature<IErrorHandlerFeature>(errorHandlerFeature);
context.Response.StatusCode = 500;
context.Response.Headers.Clear();
await _options.ErrorHandler(context);
return;
}
catch (Exception ex2)
{
_logger.LogError("An exception was thrown attempting
to execute the error handler.", ex2);
}
finally
{
context.Request.Path = originalPath;
}
throw; // Re-throw the original if we couldn't handle it
}
}
}
你需要用StartUp.cs
注册它:
public class Startup
{
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerfactory)
{
app.UseMiddleWare<ExceptionHandlerMiddleware>();
}
}
或者,如果您只想 return 任意状态代码而不关心基于异常的方法,您可以使用
return new HttpStatusCodeResult(400);
更新:从 .NET Core RC 2 开始,Http 前缀被删除。现在是:
return new StatusCodeResult(400);
我实现了自己的 HttpException
和支持中间件,它捕获所有 HttpException
并将它们转换为相应的错误响应。下面是一个简短的摘录。您还可以使用 Boxed.AspNetCore Nuget 包。
Startup.cs
中的用法示例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;
}
}
}
HttpException
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; } }
}
从长远来看,我建议不要使用异常来返回错误。异常比仅从方法返回错误要慢。
Microsoft.AspNet.Mvc.Controller
基础 class 公开了一个 HttpBadRequest(string)
重载,它将一条错误消息发送给 return 给客户端。因此,在控制器操作中,您可以调用:
return HttpBadRequest("Bad Request.");
最终我的鼻子认为从控制器操作中调用的任何私有方法都应该是完全 http 上下文感知和 return IActionResult
,或者执行一些其他完全独立于事实上,它在 http 管道内。当然这是我个人的意见,但是执行某些业务逻辑的 class 不应该 returning HTTP 状态代码,而应该抛出自己的异常,这些异常可以在controller/action级。
ASP.NET Core 本身没有等效项。正如其他人所说,实现这一点的方法是使用中间件和您自己的例外。
Opw.HttpExceptions.AspNetCore NuGet 包正是这样做的。
Middleware and extensions for returning exceptions over HTTP, e.g. as ASP.NET Core Problem Details. Problem Details are a machine-readable format for specifying errors in HTTP API responses based on https://www.rfc-editor.org/rfc/rfc7807. But you are not limited to returning exception results as Problem Details, but you can create your own mappers for your own custom formats.
它是可配置的并且有据可查。
这是开箱即用的例外列表:
4xx
- 400 BadRequestException
- 400 InvalidModelException
- 400 ValidationErrorException
- 400 InvalidFileException
- 401 未授权异常
- 403 禁止异常
- 404 NotFoundException
- 404 NotFoundException
- 409 冲突异常
- 409 ProtectedException
- 415 UnsupportedMediaTypeException
5xx
- 500 InternalServerErrorException
- 500 DbErrorException
- 500 序列化错误异常
- 503 服务不可用异常
从 ASP.NET Core 3 开始,您可以使用 ActionResult
到 return HTTP 状态代码:
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<ITEMS_TYPE> GetByItemId(int id)
{
...
if (result == null)
{
return NotFound();
}
return Ok(result);
}
这里有更多详细信息:https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1
这是@muhammad-rehan-saeed 回答的扩展版本。
它有条件地记录异常并禁用 http 缓存。
如果你使用这个和 UseDeveloperExceptionPage,你应该调用 UseDeveloperExceptionPage before this.
Startup.cs:
app.UseMiddleware<HttpExceptionMiddleware>();
HttpExceptionMiddleware.cs
/**
* Error handling: throw HTTPException(s) in business logic, generate correct response with correct httpStatusCode + short error messages.
* If the exception is a server error (status 5XX), this exception is logged.
*/
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 e)
{
var response = context.Response;
if (response.HasStarted)
{
throw;
}
int statusCode = (int) e.StatusCode;
if (statusCode >= 500 && statusCode <= 599)
{
logger.LogError(e, "Server exception");
}
response.Clear();
response.StatusCode = statusCode;
response.ContentType = "application/json; charset=utf-8";
response.Headers[HeaderNames.CacheControl] = "no-cache";
response.Headers[HeaderNames.Pragma] = "no-cache";
response.Headers[HeaderNames.Expires] = "-1";
response.Headers.Remove(HeaderNames.ETag);
var bodyObj = new {
Message = e.BaseMessage,
Status = e.StatusCode.ToString()
};
var body = JsonSerializer.Serialize(bodyObj);
await context.Response.WriteAsync(body);
}
}
}
HTTPException.cs
public class HttpException : Exception
{
public HttpStatusCode StatusCode { get; }
public HttpException(HttpStatusCode statusCode)
{
this.StatusCode = statusCode;
}
public HttpException(int httpStatusCode)
: this((HttpStatusCode) httpStatusCode)
{
}
public HttpException(HttpStatusCode statusCode, string message)
: base(message)
{
this.StatusCode = statusCode;
}
public HttpException(int httpStatusCode, string message)
: this((HttpStatusCode) httpStatusCode, message)
{
}
public HttpException(HttpStatusCode statusCode, string message, Exception inner)
: base(message, inner)
{
}
public HttpException(int httpStatusCode, string message, Exception inner)
: this((HttpStatusCode) httpStatusCode, message, inner)
{
}
}
我用这段代码得到的结果比用 :
- 使用异常处理程序:
- 自动记录每个“正常”异常(例如 404)。
- 在开发模式下禁用(当调用 app.UseDeveloperExceptionPage 时)
- 不能只捕获特定的异常
- Opw.HttpExceptions.AspNetCore:当一切正常时记录异常
另见