【问题标题】:xml string in Parameter is partially passed to API参数中的 xml 字符串部分传递给 API
【发布时间】:2018-08-25 08:18:01
【问题描述】:

在 Web API 调用期间将 xml 字符串作为查询字符串中的参数传递时遇到问题。我知道它是由于特殊的字符表示。但是不知道怎么解决。 我需要传递的xml字符串是:

<tagName name="red" query="tableName &lt;&gt; ''" requestId="requestorName:sessionID" />

但在服务方面,唯一通过的是

<tagName name="red" query="tableName

由于传递的字符串被记录为 xml,因此我无法将 &lt 替换为 。请给我一个解决方案。

我将字符串附加到客户端,如下所示:

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/xml";
var param = new NameValueCollection();
param.Add("tagName", Content);   //Content contains the xml string to be passed
client.QueryString = param;
client.DownloadString("http://localhost:8000/api/method");

我有一个如下的 Web API

[HttpGet]
[Route("api/getquery")]
public HttpResponseMessage method(string tagName)
{
  //funtions to perform
}

Web api 捕获部分字符串。

【问题讨论】:

    标签: xml rest web-services asp.net-web-api parameter-passing


    【解决方案1】:

    为我自己的查询寻找解决方案.. :D

    其实我没有考虑到的是,当我们为查询字符串添加一些参数时,完整的http请求生成如下。

    WebClient client = new WebClient();
    client.Headers[HttpRequestHeader.ContentType] = "application/xml";
    var param = new NameValueCollection();
    param.Add("tagName", Content);   //Content contains the xml string to be passed
    client.QueryString = param;
    client.DownloadString("http://localhost:8000/api/method");
    

    假设 Content 的值为“abcd”,因此 http-request 变为: "http://localhost:8000/api/method?tagName=abcd"

    现在如果添加更多参数,例如

    param.Add("tagValue", "ghij")
    

    请求是 "http://localhost:8000/api/method?tagName=abcd&tagValue=ghij"

    由于我的参数值包含特殊字符“&”,因此它会将所有发布的内容视为另一个值不匹配的参数。关键是使用“Uri.EscapeDataString()”,它实际上告诉程序将“&”视为参数值的一部分,而不是查询字符串特殊字符。

    因此正确的代码是:

    param.Add("tagName", Uri.EscapeDataString(Content));
    

    希望它也对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多