Custom exceptions to Http status codes in ASP.NET API

拥有回忆 提交于 2019-12-12 11:41:18

问题


I have a couple of custom exceptions in my business layer that bubble up to my API methods in my ASP.NET application.

Currently, they all translate to Http status 500. How do I map these custom exceptions so that I could return different Http status codes?


回答1:


This is possible using Response.StatusCode setter and getter.

Local Exception handling: For local action exception handling, put the following inside the calling code.

var responseCode = Response.StatusCode;
try
{
    // Exception was called
}
catch (BusinessLayerException1)
{
    responseCode = 201
}
catch (BusinessLayerException2)
{
    responseCode = 202
}
Response.StatusCode = responseCode;

For cross controller behavior: You should follow the below procedure.

  1. Create a abstract BaseController
  2. Make your current Controllers inherit from BaseController.
  3. Add the following logic inside BaseController.

BaseController.cs

public abstract class BaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        var responseCode = Response.StatusCode;
        var exception = filterContext.Exception;
        switch (exception.GetType().ToString())
        {
            case "ArgumentNullException":
                responseCode = 601;
                break;

            case "InvalidCastException":
                responseCode = 602;
                break;
        }
        Response.StatusCode = responseCode;
        base.OnException(filterContext);
    }
}

Note:
You can also add the exception as handled and redirecting it into some other Controller/Action

filterContext.ExceptionHandled = true;
filterContext.Result = this.RedirectToAction("Index", "Error");

More Information concerning ASP.NET MVC Error handling can be found HERE



来源:https://stackoverflow.com/questions/35539341/custom-exceptions-to-http-status-codes-in-asp-net-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!