WCF REST服务抛出500错误时无法返回带换行的纯文本
问题概述
在WCF REST Web服务中,我抛出如下异常:
throw new WebFaultException<string>("Test\r\nfailed", HttpStatusCode.InternalServerError);
浏览器返回的内容是:
"Test\r\nfailed"
我期望的返回内容是:
Test failed
详细说明
- 我在Microsoft Visual Studio Community 2022(64位)预览版17.5.0 Preview 1.0中,基于WCF服务应用程序模板创建了新应用。
- 在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>( "Test\r\nfailed", 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,浏览器显示内容为:
"Test\r\nfailed"
完整的服务器响应如下:
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 "Test\r\nfailed"
- 如果在抛出异常前执行以下代码:
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
仅会修改HTTP头中的内容类型,响应体仍为JSON编码:
Content-Type: text/plain ... "Test\r\nfailed"
- 如果执行以下代码:
System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.StatusDescription = "Bla-bla-bla";
仅会修改HTTP响应描述:
HTTP/1.1 500 Bla-bla-bla ... "Test\r\nfailed"
内容的提问来源于stack exchange,提问作者Andrew Usachov
相关产品推荐
相关产品推荐

