gpt4 book ai didi

c# - WebOperationContext.Current.OutgoingResponse.StatusCode 不工作

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:13 25 4
gpt4 key购买 nike

在 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 );

关于c# - WebOperationContext.Current.OutgoingResponse.StatusCode 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com