Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用MVC从数据体调用post API_C#_Asp.net Mvc_Api_Multipartform Data_Form Data - Fatal编程技术网

C# 使用MVC从数据体调用post API

C# 使用MVC从数据体调用post API,c#,asp.net-mvc,api,multipartform-data,form-data,C#,Asp.net Mvc,Api,Multipartform Data,Form Data,如何使用MVC客户端调用在正文消息中使用表单数据的post API API主体在表单数据中有两个属性,一个是消息,另一个是附件: 我尝试了一些方法,但由于格式错误,返回错误。这是我的代码: var client = new HttpClient(); string APIUrl = "https://mynewuploadapi.azurewebsites.net/api/v1/customers/discount"; client.Defa

如何使用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);
表单正文后的示例屏幕截图:


有人能帮我吗?谢谢

我测试了这个,它成功了:

 var client = new HttpClient();
            string APIUrl = "https://localhost:44398/api/values/test1";
            client.Timeout = TimeSpan.FromMilliseconds(1000000);
            var dict = new Dictionary<string, string>
            {
                { "message", "message" },
                { "attachements", null }
            };
            var values = new FormUrlEncodedContent(dict);
            var response = await client.PostAsync(APIUrl, values);
            response.EnsureSuccessStatusCode();
            Console.WriteLine(await response.Content.ReadAsStringAsync());
var-client=new-HttpClient();
字符串APIUrl=”https://localhost:44398/api/values/test1";
client.Timeout=TimeSpan.fromMillicons(1000000);
var dict=新字典
{
{“消息”,“消息”},
{“附件”,null}
};
var值=新的FormUrlEncodedContent(dict);
var response=wait client.PostAsync(apirl,值);
response.EnsureSuccessStatusCode();
WriteLine(wait response.Content.ReadAsStringAsync());
工作正常:


  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
                            };
                        }}

使用(var response=wait Task.Run(()=>httpClient.PostAsync(httpClient.BaseAddress,httpContent)))
{
var bodyString=await response.Content.ReadAsStringAsync();
if(response.StatusCode==HttpStatusCode.OK)
{
返回新的HttpResponseResult()
{
StatusCode=response.StatusCode,
Body=JsonConvert.DeserializeObject(bodyString),
ContentType=response.Content.Headers.ContentType?.MediaType
};
}}

这对我很有帮助

 var baseUrl = "https://mynewuploadapi.azurewebsites.net/api/v1/customers/discount";
        var token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiZXhwIjoxNTkzMzYyMTYwLCJpc3MiOiJQbHVzbWlsZXNBUEkifQ.DC42fI7dmKCTwzXPyrI5vs6Sxp0FMrOgvvr_uECzJ7Q";

        using (var httpClient = new HttpClient())
        {
         
            using (var formData = new MultipartFormDataContent())
            {
                formData.Add(new JsonContent(message), "message");
                formData.Add(new JsonContent(fileContent), "attachements");

                httpClient.Timeout = TimeSpan.FromMilliseconds(1000000);
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                var response = await httpClient.PostAsync(baseUrl, formData);
                if (!response.IsSuccessStatusCode)
                {
                    //ErrorEventArgs handling here
                }
            }
        }

首先,这是对代码中的
HttpClient.BaseAddress
误用。你必须像这样使用它:

string APIUrl = "https://mynewuploadapi.azurewebsites.net/api/v1";
client.BaseAddress = new Uri(APIUrl);

//then call api with the following
var response = await client.PostAsync("/customers/discount", content);
第二,根据目标api希望参数以何种方式发送给他,您应该了解请求结构,这里您不知道它,除非尝试执行一些测试。因此,让我们关注代码的重要部分:

授权

您采用了正确的方式发送授权持有人,即:

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
数据

您第一次尝试使用
FormUrlEncodedContent
&
StringContent
进行序列化,然后对进行两次编码,结果显示异常。您的第二次尝试遇到了在
字典
中将jsonDeserilizeFromModel用作
字符串
的问题,而这不是合并模型的方法。基于目标API中的预期请求表单,您可以使用以下解决方案之一:

解决方案A(当您可以从模型制作
字典时):

解决方案C发布为Json:

//'unitModel' is a class containing both 'message' & 'attachements'
var result = await client.PostAsJsonAsync("/customers/discount", unitModel);

我们不知道哪一个可以帮助你,因为我们无法重现你的问题。考虑到任何额外的操作,例如编码或绑定请求体可能是目标API返回错误的原因

您是否能够向我们显示控制器签名和完整的错误消息?响应结果上的消息是错误代码500。邮递员没有发送用户名和密码密码。标头中的承载JWT令牌。与源代码中的内容相同too@HoomanBahreini我只是在controllerI上用我的代码更新了我的问题我是在问控制器代码(服务器端)而不是客户端…我只是更新了我的问题,附上了邮递员成功
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent file = new StringContent("file to upload as StreamContent");
HttpContent msgItems = new FormUrlEncodedContent(model.ToDictionary());//<string, string>
form.Add(file, "attachements");
form.Add(msgItems, "message");
var response = await client.PostAsync("/customers/discount", form);
var json = JsonConvert.SerializeObject(unitModel);// or JavaScriptSerializer().Serialize
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("/customers/discount", data);
//'unitModel' is a class containing both 'message' & 'attachements'
var result = await client.PostAsJsonAsync("/customers/discount", unitModel);