我目前正在将我的 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/