首页 > 解决方案 > 使用 MVC 从数据主体调用 post API

问题描述

如何使用 MVC 客户端调用在正文消息中使用表单数据的 post API。

API 正文在表单数据中有两个属性,即消息,另一个是附件:

在此处输入图像描述

我尝试了一些方法,但由于格式错误而返回错误。这是我的代码:

var client = new HttpClient();
        string APIUrl = "https://mynewuploadapi.azurewebsites.net/api/v1/customers/discount";
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNTkzMzYyMTYwLCJpc3MiOiJQbHVzbWlsZXNBUEkifQ.DC42fI7dmKCTwzXPyrI5vs6Sxp0FMrOgvvr_uECzJ7Q");
        client.BaseAddress = new Uri("https://mynewuploadapi.azurewebsites.net/api/v1/customers/discount");
        client.Timeout = TimeSpan.FromMilliseconds(1000000);
        
        var converter = new JavaScriptSerializer().Serialize(model);
        var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("message", @converter),
            new KeyValuePair<string, string>("attachements", null)
        });

        var HTTPcontent = new StringContent(@converter, Encoding.UTF8, "multipart/form-data");

        var response = await client.PostAsync(APIUrl, HTTPcontent);

它在邮递员上工作,如下图所示: 在此处输入图像描述

这是我的控制器上的另一个尝试,它也是返回码:500

#region New Try 26Jun
        var newclient = new HttpClient();
        newclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNTkzMzYyMTYwLCJpc3MiOiJQbHVzbWlsZXNBUEkifQ.DC42fI7dmKCTwzXPyrI5vs6Sxp0FMrOgvvr_uECzJ7Q");
        newclient.Timeout = TimeSpan.FromMilliseconds(1000000);
        var dict = new Dictionary<string, string>
        {
            { "message", jsonDeserilizeFromModel},
            { "attachements", null }
        };
        var values = new FormUrlEncodedContent(dict);
        var newresponse = await newclient.PostAsync(APIUrl, values);
        newresponse.EnsureSuccessStatusCode();
        #endregion

详细邮递员电话如下: URL -https://mynewuploadapi. azurewebsites.com/api/v1/customers/discount

标题:授权:Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNTkzNDIzNzg2LCJpc3MiOiJQbHVzbWlsZXNBUEkifQ.MWa-pbYneOUKvO0_dVVXVFENwBrpU3eGWc47j1YpcmQ

身体。方法(表单发布)消息:

 {
  "tx_type": "Kad Perjalanan",
  "applicant_type": "Pekerja/Pelajar",
  "reg_type": "Permohonan Baharu",
  "ic_type": "NRIC",
  "ic_no": "821210-10-1010",
  "title": "Encik",
  "ic_name": "Ali",
  "dob": "1982-12-10",
  "gender": "Lelaki / Male",
  "mailing_address": "",
  "state": "Selangor",
  "postcode": "40000",
  "city": "Subang",
  "email": "ali@plusti.my",
  "mobile_no": "01020202020",
  "v_make": "Proton",
  "v_model": "Saga",
  "v_year": "2009",
  "v_grant": "12345",
  "v_plateno": "BTP2021VC",
  "co_name": "PLUSTI",
  "co_address": "Tepi PLUSTI Highway",
  "co_postcode": "40000",
  "co_state": "Selangor",
  "co_phone": "0375525251",
  "tngcardno": "1234554321",
  "tngcard_expiry": null,
  "rfidtagno": null,
  "v_owner": "Y",
  "discount_type":"JPP"
}

示例屏幕截图后表单正文: 在此处输入图像描述

任何人都可以帮我解决这个问题吗?谢谢

标签: c#asp.net-mvcapimultipartform-dataform-data

解决方案


它工作:


  using (var response = await Task.Run(() => httpClient.PostAsync(httpClient.BaseAddress, httpContent)))
                    {
                        var bodyString = await response.Content.ReadAsStringAsync();
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            return new HttpResponseResult<T>()
                            {
                                StatusCode = response.StatusCode,
                                Body = JsonConvert.DeserializeObject<T>(bodyString),
                                ContentType = response.Content.Headers.ContentType?.MediaType
                            };
                        }}

推荐阅读