json 无法在WCF REST Web服务中返回HTTP响应代码为500的纯文本描述

s4n0splo  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(85)

∮简而言之∮
在WCF REST Web服务中,我抛出一个异常:

throw new WebFaultException<string>("Test\r\nfailed", HttpStatusCode.InternalServerError);

浏览器返回:

"Test\r\nfailed"

我希望它返回:

Test
failed

详细描述

1.我从Microsoft Visual Studio社区2022(64位)中的WCF服务应用程序模板创建了一个新应用程序-预览版本17.5.0预览1.0。
1.我向IService1.cs添加一个新方法:

[OperationContract]
[WebInvoke(
    Method = "GET",
    UriTemplate = "Test",
    BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
string Test();

1.我将它的实现添加到Service1.cs

public string Test()
{
    throw new System.ServiceModel.Web.WebFaultException<string>(
        "Test\r\nfailed",
        System.Net.HttpStatusCode.InternalServerError);
}

1.我在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>

1.我在调试模式下启动应用程序。
将在地址http://localhost:58023处打开Web浏览器。
1.我将地址更改为http://本地主机:58023/服务1.svc/测试
浏览器将显示:

"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"
yyhrrdl8

yyhrrdl81#

如果要达到所需的效果,必须使用附加的反斜杠。

"Test \\nfailed"

如果有问题请随时与我联系。

相关问题