WebOperationContext.Current.OutgoingResponse.StatusCode 不起作用

本文关键字:不起作用 StatusCode OutgoingResponse Current WebOperationContext | 更新日期: 2023-09-27 18:30:24

在 WCF REST API 中,出于某种原因我想设置自己的状态代码 -

 WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden (or any other statuscode)

它在客户端根本不起作用:-

 using (HttpWebResponse restResponse = (HttpWebResponse)restRequest.GetResponse())
            {
                if (restResponse.StatusCode != HttpStatusCode.OK)
                {

                    retVal = String.Format("Request failed. Received HTTP {0}, Description : {1}", restResponse.StatusCode, restResponse.StatusDescription);
                    return retVal;
                }
                using (var st = restResponse.GetResponseStream())
                {
                    StreamReader sr = new StreamReader(st);
                    retVal = sr.ReadToEnd();
                    return retVal;
                }
            }

但在这里,restResponse.StatusCode始终是HttpStatusCode.OK。

我可以知道原因吗?这是怎么回事?

除此之外: -

我尝试在休息服务方法中使用以下方法 -

throw new WebFaultException<string>(<...Your message....>, HttpStatusCode.Forbidden );

但是这种方法的问题在于,在客户端.....它使代码从中出来

Try
{
    using (HttpWebResponse restResponse = (HttpWebResponse)restRequest.GetResponse())
                {
                    if (restResponse.StatusCode != HttpStatusCode.OK)
                    {

                        retVal = String.Format("Request failed. Received HTTP {0}, Description : {1}", restResponse.StatusCode, restResponse.StatusDescription);
                        return retVal;
                    }
                    using (var st = restResponse.GetResponseStream())
                    {
                        StreamReader sr = new StreamReader(st);
                        retVal = sr.ReadToEnd();
                        return retVal;
                    }
                }
}
catch
{
    //it comes here when using "throw new WebFaultException...." 
}

没有意义使用——

retVal = String.Format("Request failed. Received HTTP {0}, Description : {1}", restResponse.StatusCode, restResponse.StatusDescription);
return retVal;

有什么建议吗?

WebOperationContext.Current.OutgoingResponse.StatusCode 不起作用

在 WCF Rest API 中,您可以使用这个

throw new WebFaultException<string>(<...Your message....>, HttpStatusCode.Forbidden );