在C# Web API中处理异常有多种方法,以下是一些建议:
using System.Web.Http;
using System.Web.Routing;
using System.Web.Mvc;
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
// 处理HTTP异常,例如404、500等
Response.Clear();
Server.ClearError();
Response.StatusCode = httpException.GetHttpCode();
Response.StatusDescription = httpException.GetStatusDescription();
// 可以在这里添加自定义的错误处理逻辑,例如记录日志、发送通知等
}
else
{
// 处理其他类型的异常
Response.Clear();
Server.ClearError();
Response.StatusCode = 500;
Response.StatusDescription = "Internal Server Error";
// 可以在这里添加自定义的错误处理逻辑,例如记录日志、发送通知等
}
// 返回一个错误响应
IHttpActionResult errorResponse = new JsonResult(new
{
Code = (int)Response.StatusCode,
Message = Response.StatusDescription
});
Response.Content = JsonConvert.SerializeObject(errorResponse);
}
}
public class MyController : ApiController
{
public IHttpActionResult Get()
{
try
{
// 你的业务逻辑代码
}
catch (Exception ex)
{
// 处理异常,例如记录日志、发送通知等
return InternalServerError(ex.Message);
}
return Ok("Success");
}
}
using System.Web.Http;
using System.Web.Mvc;
public class CustomExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// 处理异常,例如记录日志、发送通知等
HttpException httpException = filterContext.Exception as HttpException;
if (httpException != null)
{
filterContext.Result = new HttpStatusCodeResult(httpException.GetHttpCode(), httpException.GetStatusDescription());
}
else
{
filterContext.Result = new HttpStatusCodeResult(500, "Internal Server Error");
}
}
}
然后,在控制器或API配置中应用此过滤器:
[CustomExceptionFilter]
public class MyController : ApiController
{
// ...
}
或者:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// ...
// 应用自定义异常过滤器
config.Filters.Add(new CustomExceptionFilterAttribute());
}
}
这些方法可以帮助你在C# Web API中处理异常,确保应用程序在遇到错误时能够返回适当的响应。