16

从我的 MVC3 控制器操作中,我想返回 HTTP 403,将“状态描述”设置为某个特定字符串,并在结果内容中返回该字符串,以便它在浏览器中可见。

我可以返回ContentResult指定内容,但不能返回状态码(例如 403),也不能返回状态描述。我可以HttpStatusCodeResult用来指定状态代码和状态描述,但不能指定结果内容。

如何制作包含所有三个的操作结果?

4

3 回答 3

17

通常,您会通过设置响应代码然后返回常规 ActionResult 来完成此操作

public ActionResult Foo() 
{ 
    Response.StatusCode = 403;
    Response.StatusDescription = "Some custom message";

    return View(); // or Content(), Json(), etc
}

如果你真的需要它成为一个 ActionResult,你可以创建你自己的。

例子:

public class HttpStatusContentResult : ActionResult
{
    private string _content;
    private HttpStatusCode _statusCode;
    private string _statusDescription;

    public HttpStatusContentResult(string content, 
                                   HttpStatusCode statusCode = HttpStatusCode.OK,
                                   string statusDescription = null)
    {
        _content = content;
        _statusCode = statusCode;
        _statusDescription = statusDescription;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.StatusCode = (int) _statusCode;
        if (_statusDescription != null)
        {
            response.StatusDescription = _statusDescription;
        }

        if (_content != null)
        {
            context.HttpContext.Response.Write(_content);
        }
    }
}
于 2013-06-26T15:52:29.990 回答
11

如果这不是太脏

Response.Clear();
Response.Write("Some specific string");
return new HttpStatusCodeResult(403, "another specific string");
于 2013-06-26T15:43:39.717 回答
-1

在我意识到问题出在 GetAwaiter().OnCompleted(...) 之前,我疯狂地试图让这段代码工作。这是我工作的版本:

public class ApiControllerBase : ApiController
{
   ...
   // Other code
   ...

   public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
   {
      return base
         .ExecuteAsync(controllerContext, cancellationToken)
         .ContinueWith(t =>
         {
            t.Result.Headers.CacheControl = new CacheControlHeaderValue()
            {
               NoStore = true,
               NoCache = true,
               MaxAge = new TimeSpan(0),
               MustRevalidate = true
            };
            t.Result.Headers.Pragma.Add(new NameValueHeaderValue("no-cache"));
            t.Result.Content.Headers.Expires = DateTime.Parse("01 Jan 1990 00:00:00 GMT");

            return t.Result;
         }, cancellationToken);
   }
}
于 2014-10-21T20:17:59.063 回答