[英]How can I return a custom HTTP status code from a WCF REST method?
如果在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,并通过一次调用将状态描述设置为404。
请注意,还有SetStatusAsCreated(Uri location) ,它将通过一次调用将状态代码设置为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());
参考: https : //social.msdn.microsoft.com/Forums/zh-CN/f6671de3-34ce-4b70-9a77-39ecf5d1b9c3/weboperationcontext-http-statuses-and-exceptions? forum =wcf
您还可以使用WebOperationContext的StatusCode和StatusDescription返回状态码和原因正文:
WebOperationContext context = WebOperationContext.Current;
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
context.OutgoingResponse.StatusDescription = "Your Message";
对于WCF数据服务,这对我不起作用。 相反,如果是数据服务,则可以使用DataServiceException。 发现以下帖子有用。 http://social.msdn.microsoft.com/Forums/zh-CN/adodotnetdataservices/thread/f0cbab98-fcd7-4248-af81-5f74b019d8de
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.