Return Mvc.JsonResult plus set Response.StatusCode

后端 未结 3 742
温柔的废话
温柔的废话 2020-12-25 10:24

Project: ASP MVC 4 running under .net 4.0 framework:

When running an application under VS 2010 express (or deployed and running under IIS 7.5 on my local machine) th

3条回答
  •  死守一世寂寞
    2020-12-25 11:16

    I've created a subclass of JsonResult that allows you to specify the HttpStatusCode.

    public class JsonResultWithHttpStatusCode : JsonResult
    {
    
        private int _statusCode;
        private string _statusDescription;
    
        public JsonResultWithHttpStatusCode(object data, HttpStatusCode status) 
        {
            var code = Convert.ToInt32(status);
            var description = HttpWorkerRequest.GetStatusDescription(code);
            Init(data, code, description);
        }
    
        public JsonResultWithHttpStatusCode(object data, int code, string description)
        {
            Init(data, code, description);
        }
    
        private void Init(object data, int code, string description)
        {
            Data = data;
            _statusCode = code;
            _statusDescription = description;
        }
    
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.StatusCode = _statusCode;
            context.HttpContext.Response.StatusDescription = _statusDescription;
            base.ExecuteResult(context);
        }
    }
    

    Then you can return this as your result and the status code will get set on the response. You can also test the status code on the result in your tests.

提交回复
热议问题