Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Masui Masanori
Masui Masanori

Posted on

     

[C#] Try sending data by HttpClient

Intro

This time, I will try sending data from a console application.

An ASP.NET Core applicaion for receiving the data

To receive the sent data, I created an ASP.NET Core.

[ASP.NET Core] HomeController.cs

usingMicrosoft.AspNetCore.Mvc;namespaceSseSample.Controllers;publicrecordSampleValue(intId,stringName);publicclassWebApiController:Controller{privatereadonlyILogger<WebApiController>logger;publicWebApiController(ILogger<WebApiController>logger){this.logger=logger;}[HttpGet][Route("/api/get")]publicstringGetWithQuery([FromQuery]intid,stringname){return$"Get Query ID:{id} Name:{name}";}[HttpPost][Route("/api/post/query/url-encoded-content")]publicstringPostWithUrlEncodedContent([FromQuery]intid,stringname){return$"PostWithUrlEncodedContent ID:{id} Name:{name}";}[HttpPost][Route("/api/post/body")]publicstringPostWithBody([FromBody]SampleValuevalue){return$"PostWithBody ID:{value.Id} Name:{value.Name}";}[HttpPost][Route("/api/post/form")]publicstringPostWithForm([FromForm]SampleValuevalue){return$"PostWithForm ID:{value.Id} Name:{value.Name}";}[HttpPost][Route("/api/post/form/file")]publicstringPostWithFileInForm([FromForm]IFormFile?file){return$"PostWithFileInForm Name:{file?.Name} FileName:{file?.FileName} Len:{file?.Length}";}}
Enter fullscreen modeExit fullscreen mode

Sending data

GET and POST with URL paramters

I can use "FormUrlEncodedContent" to add URL paramters.

[Console] Program.cs

usingSystem.Text;usingSystem.Text.Json;usingWebAccessSample;conststringBaseUrl="http://localhost:5056";usingvarhttpClient=newHttpClient();varurlParams=newDictionary<string,string>{{"id","3"},{"name","hello"}};varencodedParams=newFormUrlEncodedContent(urlParams);varparamText=awaitencodedParams.ReadAsStringAsync();Console.WriteLine(paramText);vargetResponse=awaithttpClient.GetAsync($"{BaseUrl}/api/get?{paramText}");Console.WriteLine($"/api/get{awaitgetResponse.Content.ReadAsStringAsync()}");varpostWithUrlEncodedContentResponse=awaithttpClient.PostAsync($"{BaseUrl}/api/post/query/url-encoded-content?{paramText}",newStringContent("",Encoding.UTF8,@"text/plain"));Console.WriteLine($"/api/post/query/url-encoded-content{awaitpostWithUrlEncodedContentResponse.Content.ReadAsStringAsync()}");
Enter fullscreen modeExit fullscreen mode

Results

id=3&name=hello/api/get Get Query ID: 3 Name: hello/api/post/query/url-encoded-content PostWithUrlEncodedContent ID: 3 Name: hello
Enter fullscreen modeExit fullscreen mode

I also can post like below.
But I have to remove "[FromQuery]" from "PostWithUrlEncodedContent" of the ASP.NET Core application to receive "id" value.

[Console] Program.cs

...varpostWithUrlEncodedContentResponse=awaithttpClient.PostAsync($"{BaseUrl}/api/post/query/url-encoded-content?{paramText}",encodedParams);Console.WriteLine($"/api/post/query/url-encoded-content{awaitpostWithUrlEncodedContentResponse.Content.ReadAsStringAsync()}");
Enter fullscreen modeExit fullscreen mode

POST with HTTP request body

SampleValue.cs

namespaceWebAccessSample;publicrecordSampleValue(intId,stringName);
Enter fullscreen modeExit fullscreen mode

[Console] Program.cs

...varsampleValue=newSampleValue(Id:4,Name:"world");varsampleValueJson=JsonSerializer.Serialize(sampleValue);varstringData=newStringContent(sampleValueJson,Encoding.UTF8,@"application/json");varpostWithBodyResponse=awaithttpClient.PostAsync($"{BaseUrl}/api/post/body",stringData);Console.WriteLine($"/api/post/body{awaitpostWithBodyResponse.Content.ReadAsStringAsync()}");
Enter fullscreen modeExit fullscreen mode

Results

.../api/post/body PostWithBody ID: 4 Name: world
Enter fullscreen modeExit fullscreen mode

POST with Form data

I can send JSON values as HTTP request body and receive deserialized value in the ASP.NET Core application, but I can't do the same with "MultipartFormDataContent".

[Console] Program.cs

...varmultiFormData=newMultipartFormDataContent();// I couldn't do thismultiFormData.Add(stringData,"value");varpostWithFormResponse=awaithttpClient.PostAsync($"{BaseUrl}/api/post/form",multiFormData);Console.WriteLine($"/api/post/form{awaitpostWithFormResponse.Content.ReadAsStringAsync()}");
Enter fullscreen modeExit fullscreen mode

Results

.../api/post/form PostWithForm ID: 0 Name:
Enter fullscreen modeExit fullscreen mode

I should add values like below.

varmultiFormData=newMultipartFormDataContent();// OKmultiFormData.Add(newStringContent(sampleValue.Id.ToString()),"value.Id");multiFormData.Add(newStringContent(sampleValue.Name),"value.Name");varpostWithFormResponse=awaithttpClient.PostAsync($"{BaseUrl}/api/post/form",multiFormData);Console.WriteLine($"/api/post/form{awaitpostWithFormResponse.Content.ReadAsStringAsync()}");
Enter fullscreen modeExit fullscreen mode

Results

.../api/post/form PostWithForm ID: 4 Name: world
Enter fullscreen modeExit fullscreen mode

I also receive the JSON value as string.
After receiving it, I can manually deserialize it.

[Console] Program.cs

...varmultiFormData=newMultipartFormDataContent();// OKmultiFormData.Add(stringData,"value");varpostWithFormResponse=awaithttpClient.PostAsync($"{BaseUrl}/api/post/form",multiFormData);Console.WriteLine($"/api/post/form{awaitpostWithFormResponse.Content.ReadAsStringAsync()}");
Enter fullscreen modeExit fullscreen mode

[ASP.NET Core] HomeController.cs

...[HttpPost][Route("/api/post/form")]publicstringPostWithForm([FromForm]stringvalue){varv=JsonSerializer.Deserialize<SampleValue>(value);return$"PostWithForm ID:{v?.Id} Name:{v?.Name}";}...
Enter fullscreen modeExit fullscreen mode

Results

.../api/post/form PostWithForm ID: 4 Name: world
Enter fullscreen modeExit fullscreen mode

POST with file data

[Console] Program.cs

...varmultiFormFileData=newMultipartFormDataContent();byte[]fileData;using(varmemoryStream=newMemoryStream()){using(varfileStream=newFileStream(@"./pics.png",FileMode.Open)){awaitfileStream.CopyToAsync(memoryStream);}fileData=memoryStream.ToArray();}// To send file data, I have to add "fileName"multiFormFileData.Add(newByteArrayContent(fileData),"file","pics.png");varpostWithFormFileResponse=awaithttpClient.PostAsync($"{BaseUrl}/api/post/form/file",multiFormFileData);Console.WriteLine($"/api/post/form/file{awaitpostWithFormFileResponse.Content.ReadAsStringAsync()}");
Enter fullscreen modeExit fullscreen mode

Results

.../api/post/form/file PostWithFileInForm Name: file FileName: pics.png Len: 3872061
Enter fullscreen modeExit fullscreen mode

Resources

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Programmer, husband, fatherI love C#, TypeScript, Go, etc.
  • Location
    Wakayama, Japan
  • Joined

More fromMasui Masanori

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp