如何从一个WCF REST方法返回一个自定义HTTP状态code?自定义、状态、方法、WCF

2023-09-02 20:43:32 作者:一刹时的永恒

如果出现错误的WCF REST调用,如所请求的资源是找不到的,我怎么能与HTTP响应code打(它设定成类似HTTP 404为例),在我的OperationContract的方法?

If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?

推荐答案

有一个WebOperationContext您可以访问,它有一个OutgoingResponse类型的财产OutgoingWebResponseContext其中有一个Status$c$c属性可设置

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;