Return Mvc.JsonResult plus set Response.StatusCode

后端 未结 3 743
温柔的废话
温柔的废话 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:07

    For anyone looking for this - in ASP.NET Core you can set the StatusCode property of JsonResult.

    https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.jsonresult.statuscode

    0 讨论(0)
  • 2020-12-25 11:10

    I had this exact same problem; in order to make sure that the correct answer is not buried in the comments (as it was for me), I want to reiterate @Sprockincat's comment:

    For me at least, it was indeed an issue with IIS Custom errors, and can be solved with:

    Response.TrySkipIisCustomErrors = true;
    

    @Sprockincat - you should get credit for this. I'm just making it more visible because it's such a subtle fix to a problem that is quite difficult to diagnose.

    0 讨论(0)
  • 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.

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