Return JSON with error status code MVC

前端 未结 11 1736
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 13:23

I was trying to return an error to the call to the controller as advised in This link so that client can take appropriate action. The controller is called by javascript via

11条回答
  •  北海茫月
    2020-11-27 14:04

    Building on the answer from Richard Garside, here's the ASP.Net Core version

    public class JsonErrorResult : JsonResult
    {
        private readonly HttpStatusCode _statusCode;
    
        public JsonErrorResult(object json) : this(json, HttpStatusCode.InternalServerError)
        {
        }
    
        public JsonErrorResult(object json, HttpStatusCode statusCode) : base(json)
        {
            _statusCode = statusCode;
        }
    
        public override void ExecuteResult(ActionContext context)
        {
            context.HttpContext.Response.StatusCode = (int)_statusCode;
            base.ExecuteResult(context);
        }
    
        public override Task ExecuteResultAsync(ActionContext context)
        {
            context.HttpContext.Response.StatusCode = (int)_statusCode;
            return base.ExecuteResultAsync(context);
        }
    }
    

    Then in your controller, return as follows:

    // Set a json object to return. The status code defaults to 500
    return new JsonErrorResult(new { message = "Sorry, an internal error occurred."});
    
    // Or you can override the status code
    return new JsonErrorResult(new { foo = "bar"}, HttpStatusCode.NotFound);
    

提交回复
热议问题