从我的MVC3控制器操作中,我想返回HTTP 403,将“状态描述”设置为某个特定字符串,并在结果内容中返回该字符串,以便在浏览器中显示。
我可以返回ContentResult
来指定内容,但不能返回状态代码(例如403)而不是状态描述。我可以使用HttpStatusCodeResult
指定状态代码和状态说明,但不能指定结果内容。
如何制作包含所有三个的动作结果?
答案 0 :(得分:16)
通常,您会通过设置响应代码然后返回常规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);
}
}
}
答案 1 :(得分:11)
如果这不太脏
Response.Clear();
Response.Write("Some specific string");
return new HttpStatusCodeResult(403, "another specific string");
答案 2 :(得分:-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);
}
}