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?

Anil Purswani
  • 1,857
  • 6
  • 35
  • 63

1 Answers1

2

In WCF Rest API you can use this

throw new WebFaultException<string>(<...Your message....>, HttpStatusCode.Forbidden );
tdelepine
  • 1,986
  • 1
  • 13
  • 19
  • @tdelpine, I tried to do that even, but the issue is that in this case client code comes out of "using (HttpWebResponse restResponse = (HttpWebResponse)restRequest.GetResponse())" statement and goes to the error page which I don't want. – Anil Purswani Sep 05 '13 at 20:26
  • What you want that client doing ??? turn the customErrors to off in system.web section in the web.config – tdelepine Sep 05 '13 at 20:33