Return JSON with error status code MVC

前端 未结 11 1759
隐瞒了意图╮
隐瞒了意图╮ 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:02

    You have to return JSON error object yourself after setting the StatusCode, like so ...

    if (BadRequest)
    {
        Dictionary error = new Dictionary();
        error.Add("ErrorCode", -1);
        error.Add("ErrorMessage", "Something really bad happened");
        return Json(error);
    }
    

    Another way is to have a JsonErrorModel and populate it

    public class JsonErrorModel
    {
        public int ErrorCode { get; set;}
    
        public string ErrorMessage { get; set; }
    }
    
    public ActionResult SomeMethod()
    {
    
        if (BadRequest)
        {
            var error = new JsonErrorModel
            {
                ErrorCode = -1,
                ErrorMessage = "Something really bad happened"
            };
    
            return Json(error);
        }
    
       //Return valid response
    }
    

    Take a look at the answer here as well

提交回复
热议问题