如何扩展WCF WebHttp(REST)以支持ETags和Conditional Gets?

时间:2011-06-03 22:02:47

标签: wcf rest header webhttp

我有一个只读的WCF REST服务(所有GET的宝贝!)我想为我服务中的每一项操作添加ETag /条件获取支持。

基本上我对本文中的技术扩展感兴趣: http://blogs.msdn.com/b/endpoint/archive/2010/02/25/conditional-get-and-etag-support-in-wcf-webhttp-services.aspx

我的网站有几个XML文件支持,我的应用程序知道(并引发事件),当它们中的任何一个发生变化时。我不明白扩展点在哪里。如何挂钩管道为每次调用添加这些标头而不是一次一个?

2 个答案:

答案 0 :(得分:2)

事实证明这并不是那么糟糕。我使用了IDispatchMessageInspector,我将其挂钩到ServiceBehavior中,该ServiceBehavior应用于我的所有服务。我对请求如何路由感到有点不舒服,但似乎有效。

public class ConditionalGetMessageInspector : IDispatchMessageInspector
{
    private enum GetState { Modified, Unmodified }

    private string ETag { 
        get { return XmlDataLoader.LastUpdatedTicks.ToString(); }
    }
    private DateTime LastModified { 
        get { return new DateTime(XmlDataLoader.LastUpdatedTicks);}
    }

    public object AfterReceiveRequest(ref Message request, 
        IClientChannel channel, InstanceContext instanceContext)
    {
        try
        {
            WebOperationContext.Current.IncomingRequest
                .CheckConditionalRetrieve(ETag);
        }
        catch (WebFaultException)
        {
            instanceContext.Abort();
            return GetState.Unmodified;
        }
        // No-op
        return GetState.Modified;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        if ((GetState)correlationState == GetState.Unmodified)
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode = 
                HttpStatusCode.NotModified;
            WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = 
                true;
        }
        else
        {
            WebOperationContext.Current.OutgoingResponse.SetETag(ETag);
            WebOperationContext.Current.OutgoingResponse.LastModified = 
                LastModified;
        }
    }
}

答案 1 :(得分:0)

这就是HttpOperationHandler在新的WCF Web API http://wcf.codeplex.com中的用途 我不知道是否有任何简单的方法可以使用WebHttpBinding。