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には、 SetStatusAsNotFound(string message)と呼ばれる WebOperationContext.Current.OutgoingResponse に組み込みメソッドがあり、ステータスコードを404とステータスの説明に設定しますワンコールで。
また、 SetStatusAsCreated(Uri location)があるため、1回の呼び出しでステータスコードが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 およびステータスの説明:
WebOperationContext context = WebOperationContext.Current;
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
context.OutgoingResponse.StatusDescription = "Your Message";
これは、WCF Data Servicesでは機能しませんでした。代わりに、Data Servicesの場合はDataServiceExceptionを使用できます。次の投稿が役に立つことがわかりました。 http://social.msdn.microsoft .com / Forums / en / adodotnetdataservices / thread / f0cbab98-fcd7-4248-af81-5f74b019d8de