从网页API返回控制HTTP状态code [英] Returning http status code from Web Api controller

查看:492
本文介绍了从网页API返回控制HTTP状态code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图返回304状态code不修改在Web API控制器GET方法。

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;
    }
}

这里的问题是,它不是一个例外,它只是不修改,因此客户端缓存确定。
我也想返回类型是用户(因为所有的网络API示例显示了GET)没有返回的Htt presponseMessage或这样的事情。

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.

因此​​,关键是要签名更改为的Htt presponseMessage ,并使用 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);
}

这篇关于从网页API返回控制HTTP状态code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆