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

标签 asp.net web-services unicode encoding utf-8

我有一个 ASP.NET WebService,如下所示:

[WebMethod]
public static void DoSomethingWithStrings(string stringA, string stringB)
{
    // and so on
}

第三方应用程序应调用此 Web 服务。然而,此应用程序将字符串编码为 UTF-8,并且所有元音变音都被替换为“??”。我可以查看通话,并且特殊字符的格式很好:

<?xml version="1.0" encoding="utf-8" ?>
<!-- ... -->
<SoapCall>
    <DoSomethingWithStrings>
        <stringA>Ä - Ö - Ü</stringA>
        <stringB>This is a test</stringB>
    </DoSomethingWithStrings>
</SoapCall>

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

?? - ?? - ??

This is a test

如何配置 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();
    }
}

这会读取实际的 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>

web.config 文件中,全局化设置已正确设置:

<globalization requestEncoding="UTF-8" responseEncoding="UTF-8" culture="de-DE" uiCulture="de-DE" />

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

最佳答案

最后发现接受 HTTP 消息时出现了问题。我实际上不知道是什么操纵 HTTP 请求,但我找到了解决方法。尽管 Fiddler 在我的 Application_BeginRequest 中向我展示了正确的内容类型 (text/xml; charset=utf-8),但 Request.RequestContext.HttpContext.Request.ContentType 只是 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";
}

感谢您的帮助!

关于asp.net - 在 ASP.NET WebService 中接受 UTF-8 编码的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13705359/

相关文章:

c# - 重复代码位的设计模式/C#技巧

asp.net - Google Chrome在浏览器关闭后保留 session 变量

c# - 从 dotnet 使用 Java Web 服务的最佳实践是什么

PHP 将特殊字符转换为 HTML 实体

python - Flask URL路由编码问题

asp.net - 在窗口调整大小后根据图像宽度动态更改图像高度

c# - 年、月和日参数描述了波斯历中无法表示的 DateTime

Java Web 服务错误

c# - 谷歌客户端登录授权和谷歌音乐

android - 如何使用 HttpPost 发送日语字符