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

标签 wcf rest http-status-codes operationcontext weboperationcontext

我目前正在将我的 WCF RESTful 服务从 .NET 3.5(入门工具包)迁移到 .NET 4。我使用 Visual Studio 2010 中的 WCF Rest 服务模板开始了我的项目。
我必须弄清楚如何使用 ServiceAuthorizationManager 保持我的授权方案(以前使用 RequestInterceptor 完成)。经过一些工作和研究,我完成了。
但现在我有一个抵押品问题。我的服务曾经使用 HTTP 状态代码和简要描述向我的客户反馈任何处理错误。我在我的服务方法的许多点使用 WebOperationContext 向客户描述出了什么问题,如下所示:

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

但是在 WCF 4 中,只有 StatusCode 有效 - StatusDescription 默默地失败。我不明白为什么。
我唯一的猜测是 WebOperationContext 在这个新的 WCF 4 场景中不起作用,我应该改用 OperationContext,但这也不起作用。在我的自定义类扩展 ServiceAuthorizationManager 中使用了以下方法,通知客户端由于身份验证摘要格式错误而无法访问请求:
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;
}

即使在这里使用 OperationContext direclty(WebOperationContext 的插入),StatusDescription 也不起作用。

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

最佳答案

我建议您使用 WebFaultException在 .NET 4.0 中。阅读例如"Introducing WCF WebHttp Services in .NET 4" .尝试

throw new WebFaultException<string> ("bad digest", HttpStatusCode.Forbidden);

关于WCF 4 REST 服务无法返回 StatusDescription,仅返回 StatusCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3418959/

相关文章:

c# - 如何在 VS2010 内置 Web 服务器中使用 TransportWithMessageCredential 测试 WCF 服务

c# - WCF 中的动态对象不可能吗?

Node.js、Socket.IO、Express : Should app logic be in socket handlers or REST api?

redirect - 需要登录的网页应该重定向到登录页面还是只显示表单?

c# - 如何知道 WCF 服务是否使用 protobuf-net?

c# - WCF - 发送请求的能力,其中字段可以按任何顺序排列

rest - Sugar CRM REST API 通过 POST 调用始终返回文档

java - 如何使用 postman 测试获得代码覆盖率

缺少身份验证的 HTTP 状态代码

ios - 如何处理HTTP状态码?