WebOperationContext.Current.OutgoingResponse.StatusCode无效

时间:2013-09-05 20:06:13

标签: c# .net wcf wcf-rest

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

 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;

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

在WCF Rest API中,您可以使用此

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