在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();
// 可以在這里添加自定義的錯(cuò)誤處理邏輯,例如記錄日志、發(fā)送通知等
}
else
{
// 處理其他類(lèi)型的異常
Response.Clear();
Server.ClearError();
Response.StatusCode = 500;
Response.StatusDescription = "Internal Server Error";
// 可以在這里添加自定義的錯(cuò)誤處理邏輯,例如記錄日志、發(fā)送通知等
}
// 返回一個(gè)錯(cuò)誤響應(yīng)
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
{
// 你的業(yè)務(wù)邏輯代碼
}
catch (Exception ex)
{
// 處理異常,例如記錄日志、發(fā)送通知等
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)
{
// 處理異常,例如記錄日志、發(fā)送通知等
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配置中應(yīng)用此過(guò)濾器:
[CustomExceptionFilter]
public class MyController : ApiController
{
// ...
}
或者:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// ...
// 應(yīng)用自定義異常過(guò)濾器
config.Filters.Add(new CustomExceptionFilterAttribute());
}
}
這些方法可以幫助你在C# Web API中處理異常,確保應(yīng)用程序在遇到錯(cuò)誤時(shí)能夠返回適當(dāng)?shù)捻憫?yīng)。