如果在WCF REST调用中出了点问题,例如找不到请求的资源,我该如何在OperationContract方法中使用HTTP响应代码(例如,将其设置为HTTP 404之类的东西)?
There is a WebOperationContext
that you can access and it has a OutgoingResponse
property of type OutgoingWebResponseContext
which has a StatusCode
property that can be set.
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
If you need to return a reason body then have a look at WebFaultException
For example
throw new WebFaultException<string>("Bar wasn't Foo'd", HttpStatusCode.BadRequest );
For 404 there is a built in method on the WebOperationContext.Current.OutgoingResponse called SetStatusAsNotFound(string message) that will set the status code to 404 and a status description with one call.
Note there is also, SetStatusAsCreated(Uri location) that will set the status code to 201 and location header with one call.
If you wish to see the status description in the header, REST method should make sure to return null from the Catch() section as below:
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());
You can also return a statuscode and reason body with WebOperationContext 's StatusCode and StatusDescription :
WebOperationContext context = WebOperationContext.Current;
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
context.OutgoingResponse.StatusDescription = "Your Message";
This did not work for me for WCF Data Services. Instead, you can use DataServiceException in case of Data Services. Found the following post useful. http://social.msdn.microsoft.com/Forums/en/adodotnetdataservices/thread/f0cbab98-fcd7-4248-af81-5f74b019d8de
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.