WCF 4 REST服务无法返回StatusDescription,只能返回StatusCode

Fer*_*lli 8 rest wcf http-status-codes operationcontext weboperationcontext

我目前正在将我的WCF RESTful服务从.NET 3.5(入门套件)迁移到.NET 4.我使用Visual Studio 2010中的WCF Rest服务模板启动了我的项目.我必须弄清楚如何保留我的授权方案(formely)使用ServiceAuthorizationManager完成RequestInterceptor.经过一些工作和研究,我完成了它.但现在我有了抵押问题.我的服务用于使用HTTP状态代码和简要说明向我的客户反馈任何处理错误.我在服务方法的许多方面使用WebOperationContext来向客户描述出错的地方,如下所示:

protected void returnCode(HttpStatusCode code, string description)
{
    WebOperationContext ctx = WebOperationContext.Current;
    ctx.OutgoingResponse.StatusDescription = description;
    ctx.OutgoingResponse.StatusCode = code;
}
Run Code Online (Sandbox Code Playgroud)

但在WCF 4中,只有StatusCode工作 - StatusDescription静默失败.我无法弄清楚为什么.我唯一的猜测是WebOperationContext在这个新的WCF 4场景中不起作用,我应该使用OperationContext,但这也行不通.在我的自定义类中使用以下方法扩展ServiceAuthorizationManager,通知客户端请求无法访问,因为auth摘要格式错误:

private void GenerateBadDigestMessage(ref OperationContext operationContext)
{
    Message reply = Message.CreateMessage(MessageVersion.None, null, null, new DataContractJsonSerializer(typeof(object)));

    HttpResponseMessageProperty hrp = new HttpResponseMessageProperty();
    hrp.StatusCode = HttpStatusCode.Forbidden;
    hrp.StatusDescription = "bad digest";
    reply.Properties[HttpResponseMessageProperty.Name] = hrp;

    operationContext.RequestContext.Reply(reply);
    operationContext.RequestContext = null;
}
Run Code Online (Sandbox Code Playgroud)

即使在这里使用OperationContext direclty(由WebOperationContext提供),StatusDescription也不起作用.

我在这里缺少什么?为什么这么小的东西可以从.NET 3.5打破到4?

Ole*_*leg 4

WebFaultException我建议您在.NET 4.0中使用。例如,阅读“.NET 4 中的 WCF WebHttp 服务简介”。尝试

throw new WebFaultException<string> ("bad digest", HttpStatusCode.Forbidden);
Run Code Online (Sandbox Code Playgroud)