阅读量:0
在C# WebAPI中处理异常通常可以通过以下方法:
- 使用try-catch块捕获异常并返回相应的错误信息。
try { // code that may throw an exception } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An error occurred: " + ex.Message); }
- 使用全局异常过滤器处理所有发生的异常。
public class CustomExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("An error occurred: " + context.Exception.Message), ReasonPhrase = "Internal Server Error" }; context.Response = response; } }
- 使用ExceptionHandler中间件处理全局异常。
public class Startup { public void Configuration(IAppBuilder app) { app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { var ex = context.Error; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("An error occurred: " + ex.Message); }); }); } }
这些方法可以帮助您在C# WebAPI中有效地处理异常,根据具体需求选择合适的方式来处理异常。