Return JSON with error status code MVC

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

    Several of the responses rely on an exception being thrown and having it handled in the OnException override. In my case, I wanted to return statuses such as bad request if the user, say, had passed in a bad ID. What works for me is to use the ControllerContext:

    var jsonResult = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = "whoops" };
    
    ControllerContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    
    return jsonResult;
    

提交回复
热议问题