2

In WCF REST API I would like to set own StatusCode for some reason -

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

it doesn't work at all as in the client end : -

 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;
                }
            }

but here the restResponse.StatusCode is always HttpStatusCode.OK.

May I know the reason? What is wrong here?

Addition to it: -

I tried using following in Rest Service Method --

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

but the issue with this approach is that at client end.....it makes the code to come out of

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...." 
}

there is no point to use --

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

Any suggestions?

4

1 回答 1

2

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

throw new WebFaultException<string>(<...Your message....>, HttpStatusCode.Forbidden );
于 2013-09-05T20:11:00.703 回答