在 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。
我可以知道原因吗?这里有什么问题?
对它的补充:-
我尝试在 Rest 服务方法中使用以下内容 --
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;
有什么建议吗?
在 WCF Rest API 中你可以使用这个
throw new WebFaultException<string>(<...Your message....>, HttpStatusCode.Forbidden );
我是一名优秀的程序员,十分优秀!