总之
在WCF REST web服务中,我抛出一个异常:
throw new WebFaultException<string>("Testrnfailed", HttpStatusCode.InternalServerError);
浏览器返回:
"Testrnfailed"
我想让它返回:
Test
failed
<标题>详细描述我创建了一个新的应用程序从WCF服务应用程序模板Microsoft Visual Studio Community2022(64位)-预览版17.5.0。
我添加了一个新方法到IService1.cs:
[OperationContract]
[WebInvoke(
Method = "GET",
UriTemplate = "Test",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string Test();
- 我将它的实现添加到Service1.cs:
public string Test()
{
throw new System.ServiceModel.Web.WebFaultException<string>(
"Testrnfailed",
System.Net.HttpStatusCode.InternalServerError);
}
- 我在Web.config中将服务类型从SOAP更改为REST:
<system.serviceModel>
<services>
<service name="WcfService1.Service1">
<endpoint binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="rest" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="rest">
<webHttp/>
</behavior>
</endpointBehaviors>
...
</behaviors>
...
</system.serviceModel>
- 我以调试模式启动应用程序。
浏览器打开地址http://localhost:58023.
- 我将地址更改为http://localhost:58023/Service1.svc/Test。
浏览器显示:
"Testrnfailed"
完整的服务器回复是:
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?V2h5IHRoZSBoZWxsIGFyZSB5b3UgdHJ5aW5nIHRvIGRlY29kZSB0aGlzPw?=
X-Powered-By: ASP.NET
Date: Fri, 09 Dec 2022 15:53:19 GMT
Connection: close
Content-Length: 16
"Testrnfailed"
如果在抛出异常之前执行以下操作:
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
它只改变HTTP报头中的内容类型,正文保持json编码:
Content-Type: text/plain
...
"Testrnfailed"
如果我做以下操作:
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.StatusDescription = "Bla-bla-bla";
它只改变HTTP响应描述:
HTTP/1.1 500 Bla-bla-bla
...
"Testrnfailed"
标题>如果你想达到你想要的效果,你必须使用一个额外的反斜杠。
"Test \nfailed"
如有问题请随时与我联系。