从.net核心以Content-Type:multipart / form-data调用POST API

时间:2019-03-06 03:40:59

标签: .net post .net-core dotnet-httpclient

我必须从.net核心Web应用程序中调用post api,该API接受参数作为表单数据。我可以从邮递员那里调用API,但是从.net核心应用程序调用时出现错误。看下面我的代码和邮递员的参数。

// POST api/values
    [HttpPost]
    public async Task Post()
    {
        using (HttpClient client = new HttpClient())
        {
            // Call asynchronous network methods in a try/catch block to handle exceptions
            try 
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Authorization = 
                    new AuthenticationHeaderValue(
                        "Bearer", 
                        "**************************************");
                var multiContent = new MultipartFormDataContent();
                multiContent.Add(new StringContent("Test Name"), "Name");
                multiContent.Add(new StringContent("Test Type"), "Type");
                multiContent.Add(new StringContent("100"), "Min");
                multiContent.Add(new StringContent("100"), "Max");
                multiContent.Add(new StringContent("100"), "Amount");

                HttpResponseMessage response = await 
                client.PostAsync
                ("https://test/api"
                , multiContent);

                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                Console.WriteLine(responseBody);
            }  
            catch(HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");   
                Console.WriteLine("Message :{0} ",e.Message);
            }
        }
    }

enter image description here

0 个答案:

没有答案