繁体   English   中英

如何在 C# 中使用表单数据构造 HttpClient POST 请求?

[英]How to construct HttpClient POST Request with form-data in C#?

我在使用 HTTPClient 在 C# 中使用表单数据构建 POST 请求时遇到问题。 我尝试了多种方法,但似乎没有任何效果。 你能帮助我所缺少的吗?

请注意,SWAGGER POST 工作正常,基于此我正在尝试构建请求。

API参数

rPath* string
(formData)
nName* string
(formData)
nFile string
(formData)
type* string
(formData)  
zFile file
file

工作招摇的POST

curl -X POST "http://localhost:8888/server/api/v1.0/createfolder" -H "accept: text/plain; charset=UTF-8" -H "authorization: Basic XXXXXXX" -H "Content-Type: multipart/form-data" -F "rPath=/RootFolder/" -F "nName=testing" -F "type=Folder"

SWAGGER POST 的 Fiddler 请求标头(这是有效的)。

提琴手请求详细信息

    static void Main(string[] args)
    {
        var formData = new MultipartFormDataContent();
        HttpContent content = new FormUrlEncodedContent (new[]
        {
            new KeyValuePair<string, string>("rPath",  "/RootFolder/"),
            new KeyValuePair<string, string>("nName", "TestFolder"),
            new KeyValuePair<string, string>("type", "Folder")
        });           
        content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
         formData.Add(content);
        var url = "http://localhost:8888/server/api/v1.0/createfolder";
        HttpResponseMessage response = PostRoot(formData, url);
    }
    static HttpResponseMessage PostRoot(HttpContent content, string webMethod)
    {
        HttpResponseMessage response = new HttpResponseMessage();
        using (var client = new HttpClient() {  })
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "xxxxxxx=");
            response = client.PostAsync(webMethod, content).Result;
        }

        return response;
    }
var client = new HttpClient();
var baseUrl = "https://someurl";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");
var formContent = new MultipartFormDataContent
{
 {new StringContent("Value1"),"formparamname1"},
 {new StringContent("Value2"),"formparamname2" },
 {new StringContent("Value2"),"formparamname3"},
};
var response = client.PostAsync(baseUrl, formContent).Result;
response.EnsureSuccessStatusCode();
var result = string.Empty;
if (response.IsSuccessStatusCode)
 {
   result = response.Content.ReadAsStringAsync().Result;
 }
return result;

暂无
暂无

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

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