简体   繁体   English

如何在 Post-C# 中使用 RestClient 传递 Xml 文件?

[英]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.我正在尝试使用 RestSharp 将 xml 文件传递给 api,但我在 Post 方法中接收的文件为 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.我不使用 XML,所以这与您的示例略有不同,但将 XML 发布到 [HttpPost] API 端点是一个可行的选择。 I used your SendXmlToApi() example untouched (just supplied my own _uri and XmpPath variables) and was successful (Core 3.1).我使用了您的SendXmlToApi()示例,原样(仅提供了我自己的_uriXmpPath变量)并且成功(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.当然,您会希望在此设置防护栏并进行适当的错误处理和验证,但这应该可以帮助您克服困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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