How to return HTTP 500 from ASP.NET Core RC2 Web Api?

前端 未结 8 2411
忘掉有多难
忘掉有多难 2020-12-04 17:01

Back in RC1, I would do this:

[HttpPost]
public IActionResult Post([FromBody]string something)
{    
    try{
        // ...
    }
    catch(Exception e)
            


        
相关标签:
8条回答
  • 2020-12-04 17:55

    How about creating a custom ObjectResult class that represents an Internal Server Error like the one for OkObjectResult? You can put a simple method in your own base class so that you can easily generate the InternalServerError and return it just like you do Ok() or BadRequest().

    [Route("api/[controller]")]
    [ApiController]
    public class MyController : MyControllerBase
    {
        [HttpGet]
        [Route("{key}")]
        public IActionResult Get(int key)
        {
            try
            {
                //do something that fails
            }
            catch (Exception e)
            {
                LogException(e);
                return InternalServerError();
            }
        }
    }
    
    public class MyControllerBase : ControllerBase
    {
        public InternalServerErrorObjectResult InternalServerError()
        {
            return new InternalServerErrorObjectResult();
        }
    
        public InternalServerErrorObjectResult InternalServerError(object value)
        {
            return new InternalServerErrorObjectResult(value);
        }
    }
    
    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object value) : base(value)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    
        public InternalServerErrorObjectResult() : this(null)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:59
    return StatusCode((int)HttpStatusCode.InternalServerError, e);
    

    Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).

    HttpStatusCode is an enumeration in System.Net.

    0 讨论(0)
提交回复
热议问题