在C# WebAPI中处理异常通常可以通过以下方法:
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;
}
}
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中有效地处理异常,根据具体需求选择合适的方式来处理异常。