使用 C# 在 HttpPost 中接收 XML

Receiving XML in HttpPost Using C#

我认为这会很容易,但事实并非如此 - 至少对我而言。我正在尝试将 XML 字符串发送到 REST 端点。此时,端点唯一要做的就是将 XML 记录到文件或数据库中。 XML 本身是未知的,它实际上可以是任意长度并且具有任意数量的节点。所以它真的需要被当作一个字符串来对待。

我的问题是我无法确定如何在 Post 方法中接收 XML/string。我正在使用 RestSharp 库。

这是我正在使用的 Post 方法;很简单的。我删除了日志记录代码和 try/catch 代码以保持简单。

[HttpPost]
public IHttpActionResult Post([FromBody] string status)
{
    // Log the post into the DB
    LogPost(status);
}

执行post的代码:

public void TestPost()
{
    IRestResponse response;
    try
    {
        // Get the base url for 
        var url = @"http://blahblah/status";
        // Create the XML content
        object xmlContent = "<XML><test><name>Mark</name></test></XML>";
        var client = new RestClient(url);
        var request = new RestRequest(Method.POST);
        // Add required headers
        request.AddHeader("Content-Type", "text/plain");
        request.AddHeader("cache-control", "no-cache");
        request.AddJsonBody(xmlContent);
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        response = client.Execute(request);
    }
    catch (Exception ex)
    {
       ...
    }
}

问题:post 接收到的状态参数很简单,就是 "Mark"。完整的 XML 不见了!我需要整个 XML 字符串。

我已经尝试了几种不同的变体。将内容类型更改为 "application/xml"、"application/json" 等。没有任何效果。

我尝试过使用 request.AddXmlBody(statusObject) 和 request.AddBody(statusObject)。都没有成功。

我什至尝试使用 request.AddHeader() 发送 XML,但没有成功。我错过了什么。一定有一些明显的东西我没有得到。

您是否尝试使用

发送请求

Content-Type: application/xml; charset="utf-8"

而不是 text\plain?

a) 您必须配置 Web API 才能在您的 WebApiConfig.Register 中使用 XmlSerializer。否则 Web API 默认使用 DataContractSerializer。

文件:App_Start\WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Formatters.XmlFormatter.UseXmlSerializer = true; //HERE!
        ...
    }

b) 你需要为你的 xml

定义一个 class
    public class test { public string name { get; set; } } //BASED ON YOUR XML NODE

    [HttpPost]
    public IHttpActionResult Post([FromBody] string status)
    {

    }

c) 如果您需要使用简单的字符串,请更改 POST 方法

    public void Post(HttpRequestMessage request)
    {
        string body = request.Content.ReadAsStringAsync().Result;

    }

d) 从 restsharp 客户端调用

            string xmlContent = "<test><name>Mark</name></test>"; 
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.AddParameter("application/xml", xmlContent, ParameterType.RequestBody); 
            var response = client.Execute(request);

由于 "some" 原因 request.AddParameter 将第一个参数作为 ContentType(不是名称) https://github.com/restsharp/RestSharp/issues/901