在 ASP.NET WebService 中接受 UTF-8 编码的字符串

Car*_*ten 4 asp.net unicode encoding web-services utf-8

我有一个 ASP.NET WebService,它看起来像这样:

[WebMethod]
public static void DoSomethingWithStrings(string stringA, string stringB)
{
    // and so on
}
Run Code Online (Sandbox Code Playgroud)

第三方应用程序应调用此网络服务。但是,此应用程序将字符串编码为 UTF-8,并且所有变音符号都被替换为“??”。我可以查看呼叫并且特殊字符的格式很好:

<?xml version="1.0" encoding="utf-8" ?>
<!-- ... -->
<SoapCall>
    <DoSomethingWithStrings>
        <stringA>Ä - Ö - Ü</stringA>
        <stringB>This is a test</stringB>
    </DoSomethingWithStrings>
</SoapCall>
Run Code Online (Sandbox Code Playgroud)

当我简单地打印 webservice 方法中的字符串时,这会产生以下输出:

?? - ?? - ??

这是一个测试

如何配置 WebService 以接受 UTF-8 编码的字符串?

更新

Fiddler 还告诉我 http 请求的内容类型字符集是 UTF-8。

更新 2

我尝试添加以下代码以global.asax进行调试:

public void Application_BeginRequest(object sender, EventArgs e)
{
    using (var reader = new System.IO.StreamReader(Request.InputStream))
    {
        string str = reader.ReadToEnd();
    }
}
Run Code Online (Sandbox Code Playgroud)

这将读取实际的 SOAP 调用。该StreamReader小号编码设置为UTF-8。SOAP 调用看起来正确:

<?xml version="1.0" encoding="UTF-8" ?> 
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <DoSomethingWithStrings xmlns="http://www.tempuri.org/">
            <stringA>Ä - Ö - Ü</stringA>
            <stringB>This is a test!</stringB>
        </DoSomethingWithStrings>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Run Code Online (Sandbox Code Playgroud)

web.config文件中正确设置了全球化设置:

<globalization requestEncoding="UTF-8" responseEncoding="UTF-8" culture="de-DE" uiCulture="de-DE" />
Run Code Online (Sandbox Code Playgroud)

所以看起来反序列化 SOAP 消息的东西不使用 UTF-8 而是 ASCII 编码。

Car*_*ten 6

最后发现在接受 HTTP 消息时出了点问题。我实际上不知道是什么操纵了 HTTP 请求,但我找到了一个解决方法。尽管 Fiddlertext/xml; charset=utf-8在我Application_BeginRequestRequest.RequestContext.HttpContext.Request.ContentTypejust 中向我展示了正确的内容类型 ( ) text/xml,这导致在 ASMX 序列化程序中回退到默认 (ASCII) 编码。我已将以下代码添加到Application_BeginRequest处理程序中,现在一切正常。

if (Request.RequestContext.HttpContext.Request.ContentType.Equals("text/xml"))
{
    Request.RequestContext.HttpContext.Request.ContentType = "text/xml; charset=UTF-8";
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!