从 Web Api 控制器返回 http 状态代码 [英] Returning http status code from Web Api controller
问题描述
我正在尝试为 Web api 控制器中的 GET 方法返回未修改的 304 状态代码.
I'm trying to return a status code of 304 not modified for a GET method in a web api controller.
我成功的唯一方法是这样的:
The only way I succeeded was something like this:
public class TryController : ApiController
{
public User GetUser(int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
throw new HttpResponseException(HttpStatusCode.NotModified);
}
return user;
}
}
这里的问题是它不是一个例外,它只是没有被修改所以客户端缓存是可以的.我还希望返回类型是用户(如所有 web api 示例显示的 GET)不返回 HttpResponseMessage 或类似的东西.
The problem here is that it's not an exception, It's just not modified so the client cache is OK. I also want the return type to be a User (as all the web api examples shows with GET) not return HttpResponseMessage or something like this.
推荐答案
我不知道答案所以问了 ASP.NET 团队 此处.
I did not know the answer so asked the ASP.NET team here.
所以诀窍是将签名更改为 HttpResponseMessage
并使用 Request.CreateResponse
.
So the trick is to change the signature to HttpResponseMessage
and use Request.CreateResponse
.
[ResponseType(typeof(User))]
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
var user = new DataEntities().Users.First(p => p.Id == userId);
if (user.LastModified <= lastModifiedAtClient)
{
return new HttpResponseMessage(HttpStatusCode.NotModified);
}
return request.CreateResponse(HttpStatusCode.OK, user);
}
这篇关于从 Web Api 控制器返回 http 状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!