How to add Content-Type: application/octet-stream to .Net Core header - asp.net-core

I want to accomplish this, is there any trick
HttpClient c = new HttpClient();
c.DefaultRequestHeaders.Add("Content-type", "application/octet-stream"));

You should set content headers with HttpContent object, like below.
var client = _clientFactory.CreateClient();
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
var response = await client.PostAsync(uri, content);
//code logic here
//...
}
Besides, for more information about using IHttpClientFactory to create an HttpClient instance in ASP.NET Core, please check: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1

Related

CS1503: Argument 2: cannot convert from ‘System.Net.Http.HttpContent’ to ‘System.Net.Http.HttpCompletionOption’

I'm trying to make a call to another microservice's get method from a service. But when I try to do so, I'm getting this error:
CS1503: Argument 2: cannot convert from ‘System.Net.Http.HttpContent’ to ‘System.Net.Http.HttpCompletionOption’.
Below is the code in the source microservice to get a list of data from the destination service.
this._httpClient.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "relativeAddress");
request.Content = new StringContent(JsonConvert.SerializeObject(invoiceFilterRequest),
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
var response = await this._httpClient.GetAsync(InvEndpoints.GET_Cus_List, request.Content).ConfigureAwait(false);
Actual error is shown in the 2nd parameter request.Content in the GetAsync() call.
Here is the destination service method:
[HttpGet("cus/filter")]
public async Task<ActionResult<PagedList<Inv>>> GetCusByFilterAsync(InvFilterRequest request)
{
try
{
//..
}
}
Is there any simple solution to send object as a parameter using HTTP GET to another microservice other than sending them as a query string using the above code?
Please check the GetAsync(String, HttpCompletionOption) method, when using the GetAsync method, the second parameter should be the HttpCompletionOption, instead of HttpContent.
From your description, it seems that you want to send a request with parameters, if that is the case, you should use the HttpClient.PostAsync method, instead of the HttpClient.GetAsync method, refer the following sample:
var companyForCreation = new CompanyForCreationDto
{
Name = "Eagle IT Ltd.",
Country = "USA",
Address = "Eagle IT Street 289"
};
var company = JsonSerializer.Serialize(companyForCreation);
var requestContent = new StringContent(company, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("companies", requestContent);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var createdCompany = JsonSerializer.Deserialize<CompanyDto>(content, _options);
Reference: Make HTTP requests using IHttpClientFactory in ASP.NET Cor

Sending data to PowerFlow from ASP.Net Core App

I am trying to post data to Power Automate HTTP Request trigger, but i just get all properties with Null values. I dont know what i am missing?
It is requeried to set "Content-Type":"application/json".
(blog post referecne: https://flow.microsoft.com/en-us/blog/call-flow-restapi/ )
My .Net corre app code is:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
var response = await client.PostAsJsonAsync(url, order);
response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsAsync<String>();
http post data
I test it in my side, you can refer to my power-automate flow and my .net code below:
My flow shown as:
And my code shown as below:
using System;
using System.Net.Http;
using System.Text;
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var postData = "{\"name\": \"Hury\",\"email\": \"test#xxx.com\"}";
HttpContent httpContent = new StringContent(postData, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var response = client.PostAsync("your http request trigger url", httpContent);
Console.WriteLine(response.Result);
}
}
}
After running this code, we can see the properties are post success from the request in the running history.

Receive IFileForm in Net Core Controller and forward to another (independent) API

I have an Vue.JS application, where I upload an image to a NetCore Controller.
I'm receiving the IFileForm in the following controller:
[HttpPost("UpdateContactPhoto")]
public async Task<string> UpdateContactPhoto(IFormFile file){ //Forward the original IFileForm to another NetCore API. }
At this point everything is working correctly. IFileForm arrives perfect.
My problem is that I need to forward this IFileForm to another API (independent of this) whose input is an IFileForm with HttpClient PutAsync, but not works.
Can someone help me?
Thanks for help.
You can use this example. Note that the argument name is the same as the item added to the form-data:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:57985");
byte[] data;
using (var br = new BinaryReader(file.OpenReadStream()))
{
data = br.ReadBytes((int) file.OpenReadStream().Length);
}
ByteArrayContent bytes = new ByteArrayContent(data);
MultipartFormDataContent multiContent = new MultipartFormDataContent();
multiContent.Add(bytes, "file", file.FileName);
var result = client.PutAsync("api/v1/FileManager", multiContent).Result;
if (result.StatusCode == HttpStatusCode.OK)
{
//do some things
}
}
You can also use this code to get the file from the HttpContext :
IFormFile file = HttpContext.Request.Form.Files[0];
Replace "Target url here" with your destination URL:
HttpClient httpClient = new HttpClient();
var streamcontent = new StreamContent(file.OpenReadStream());
var response = await httpClient.PutAsync("target url here", streamcontent);
Reference:
HttpClient PutAsync
StreamContent class
IFormFile interface

Sending Multipart form data from windows phone to web api

Hi I want to send(post/put) some data(containing string, int and Stream) from windows phone 8.1 using HttpClient to web api. what is the best way to do that.
public async void Put(string uri)
{
var httpClient = new System.Net.Http.HttpClient();
MultipartFormDataContent content = new MultipartFormDataContent();
var stringContent = new StringContent("FirstName=MUH&LastName=Test", Encoding.UTF8, "multipart/form-data");
var test = new StreamContent(new MemoryStream());
content.Add(test);
content.Add(stringContent);
var message = await httpClient.PutAsync(url+"/UpdateTest", content);
message.EnsureSuccessStatusCode();
string content1 = await message.Content.ReadAsStringAsync();
}
api method in my mvc app
[AllowAnonymous]
[Route("~/api/account/UpdateTest")]
[HttpPut]
public async Task<object> UpdateTest()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
try
{
var requestParts = await Request.Content.ReadAsMultipartAsync();
foreach (var part in requestParts.Contents)
{
//part is always StreamContent
var test = await part.ReadAsStreamAsync();
var test1 = await part.ReadAsStringAsync();
}
}
catch (Exception ex)
{ }
}
In my windows phone project I have passed 2 HttpContent, one is StreamContent where as other is StringContent. but in my web api put method both are StreamContent I do't know why.
and other problem is I have to parse the string key value in StingContnet. My question is what is the best way of sending/receiving multipart form data from windows phone 8.1 to web api,
Thanks
Following is an example(change this accordingly to your scenario):
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
HttpRequestMessage request = new HttpRequestMessage();
MultipartFormDataContent mfdc = new MultipartFormDataContent();
mfdc.Add(new StringContent("Michael"), name: "FirstName");
mfdc.Add(new StringContent("Jordan"), name: "LastName");
mfdc.Add(new StreamContent(content: new MemoryStream(Encoding.UTF8.GetBytes("This is from a file"))),
name: "Data",
fileName: "File1.txt");
HttpResponseMessage response = await client.PostAsync(baseAddress + "/api/values", mfdc);
public async Task Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
MultipartFormDataStreamProvider prov = await Request.Content.ReadAsMultipartAsync<MultipartFormDataStreamProvider>(new MultipartFormDataStreamProvider(#"C:\uploadedfiles"));
// example of how you can read the form data
string firstName = prov.FormData["FirstName"];
// Get list of all files that have been uploaded and stored in the above provided root folder
Collection<MultipartFileData> files = prov.FileData;
}
Following is how request looks like in Fiddler tool:
POST http://localhost:9095/api/values HTTP/1.1
Content-Type: multipart/form-data; boundary="7560a854-a71a-4e55-9571-5c2de520f45f"
Host: kirandesktop:9095
Content-Length: 474
Expect: 100-continue
Connection: Keep-Alive
--7560a854-a71a-4e55-9571-5c2de520f45f
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=FirstName
Michael
--7560a854-a71a-4e55-9571-5c2de520f45f
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=LastName
Jordan
--7560a854-a71a-4e55-9571-5c2de520f45f
Content-Disposition: form-data; name=Data; filename=File1.txt; filename*=utf-8''File1.txt
This is from a file
--7560a854-a71a-4e55-9571-5c2de520f45f--
Also note that you can read the StreamContent anyway you want...in the following examples, I am simulating a request's body stream and reading it as a simple string or deserializing into an object of type Person.
StreamContent requestStream = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("Hello World!")));
string data = await requestStream.ReadAsStringAsync();
//---------------------
StreamContent requestStream = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes("{ \"FirstName\" : \"Michael\" }")));
requestStream.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Person person = await requestStream.ReadAsAsync<Person>();
I use a custom media type formatter that's based on the code in this article.
ASP.NET WebApi: MultipartDataMediaFormatter
One of the advantages over the MultipartFormDataStreamProvider is that I don't need to specify a folder to save the file data, so I can inspect the contents in memory. You might not want to do this with huge files though. There's alot a github repo for it too if you want to look at the code. Also, I get strongly typed objects for file and form data

How to consume REST service from a MVC 4 web application?

Can someone give me pointers on how to How to consume an external REST service from a MVC 4 web application? The services rely on an initial call with credentials base 64 encoded, then returns a token which is used for further web service queries.
I cannot find an easy primer on how to do this kind of thing, could someone help please?
I have all this working in classic ASP & JQuery but need to move over to an MVC 4 web application.
You could use the HttpClient class. Here's an example of how you could send a GET request and use Basic Authentication:
var client = new HttpClient();
client.BaseAddress = new Uri("http://foo.com");
var buffer = Encoding.ASCII.GetBytes("john:secret");
var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));
client.DefaultRequestHeaders.Authorization = authHeader;
var response = client.GetAsync("/api/authenticate").Result;
if (response.IsSuccessStatusCode)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
}
Once you have retrieved the access token you could make authenticated calls:
var client = new HttpClient();
client.BaseAddress = new Uri("http://foo.com");
string accessToken = ...
var authHeader = new AuthenticationHeaderValue("Bearar", accessToken);
client.DefaultRequestHeaders.Authorization = authHeader;
var response = client.GetAsync("/api/bar").Result;
if (response.IsSuccessStatusCode)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
}