如果WCF REST调用出现问题,例如请求的资源未找到,我应该如何在我的OperationContract方法中操作HTTP响应代码(将其设置为类似于HTTP 404的内容)?
有一个WebOperationContext
可以访问,它具有一个类型为OutgoingWebResponseContext
的属性OutgoingResponse
,它有一个可以设置的StatusCode
属性。
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
WebFaultException
似乎有效。 - Josh M.throw new WebFaultException<string>("Bar wasn't Foo'd", HttpStatusCode.BadRequest );
对于404错误,WebOperationContext.Current.OutgoingResponse内置了一个名为SetStatusAsNotFound(string message)的方法,它可以一次调用设置状态码为404并设置状态描述。
注意,还有一个名为SetStatusAsCreated(Uri location)的方法,它可以一次调用将状态码设置为201并设置位置头。
WebOperationContext context = WebOperationContext.Current;
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
context.OutgoingResponse.StatusDescription = "Your Message";
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());
这对于WCF数据服务对我没有用。相反,您可以在使用数据服务时使用DataServiceException。我发现以下帖子很有用。 http://social.msdn.microsoft.com/Forums/en/adodotnetdataservices/thread/f0cbab98-fcd7-4248-af81-5f74b019d8de