[英]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.