简体   繁体   中英

How to pass Xml file using RestClient in Post - C#?

I'm trying to pass xml file to api using RestSharp, but I'm receiving the file at the Post method as null.

Here is my code:

 public void SendXmlToApi()
    {
        var client = new RestClient(_uri);
        var request = new RestRequest(Method.POST);
        request.AddFile("Xml",XmlPath);
        request.RequestFormat = DataFormat.Xml;
        request.AddHeader("content-type", "application/xml");
        var response = client.Execute(request);
        bool res = (response.StatusCode == HttpStatusCode.OK);
    }

And my Post Func:

   [HttpPost]
    [Route("Test")]
    public void UpdateResult(XDocument a)
    {

        
    }

Any idea whats the problem?

I don't use XML, so this deviates a little from your example, but it is a viable option for posting XML into a [HttpPost] API endpoint. I used your SendXmlToApi() example untouched (just supplied my own _uri and XmpPath variables) and was successful (Core 3.1).

I modified your receiving code to be:

[HttpPost]
[Route("test")]
public async Task UpdateResult()
{
    string body = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
    XDocument xdoc = XDocument.Parse(body);
}

Of course, you'll want to put guard rails on this and have proper error handling and validation, but it should get you over the hump.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM