如何从WCF REST方法返回自定义HTTP状态代码?
题
如果在WCF REST调用中出现问题,例如找不到请求的资源,我如何在我的OperationContract方法中使用HTTP响应代码(例如,将其设置为HTTP 404)?
解决方案
WebOperationContext
您可以访问,它有 OutgoingResponse 属性 OutgoingWebResponseContext
,其中包含 StatusCode
属性。
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
其他提示
如果您需要返回原因主体,请查看 WebFaultException
例如
throw new WebFaultException<string>("Bar wasn't Foo'd", HttpStatusCode.BadRequest );
对于404, WebOperationContext.Current.OutgoingResponse 上有一个内置方法,名为 SetStatusAsNotFound(字符串消息),它将状态代码设置为404并显示状态说明一个电话。
注意还有 SetStatusAsCreated(Uri位置),它会将状态代码设置为201,并通过一次调用设置位置标题。
如果您希望在标题中看到状态描述,REST方法应确保从Catch()部分返回null,如下所示:
catch (ArgumentException ex)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message;
return null;
}
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
throw new WebException("令牌码不正确", new InvalidTokenException());
您还可以使用 WebOperationContext 的 StatusCode 和 StatusDescription :
WebOperationContext context = WebOperationContext.Current;
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
context.OutgoingResponse.StatusDescription = "Your Message";
这对我来说对WCF数据服务不起作用。相反,您可以在Data Services的情况下使用DataServiceException。发现以下帖子有用。 http://social.msdn.microsoft的.com /论坛/ EN / adodotnetdataservices /线程/ f0cbab98-fcd7-4248-af81-5f74b019d8de
不隶属于 StackOverflow