How to add Header values to HttpWebRequest in .Net Core - asp.net-core

I am developing simple Http client to consume an Asp.Net Core Web API. I want to pass few http header values to the Web API via HttpHeaderCollection. In previous versions of .Net framework allowed to add header values to the HttpHeaderCollection as following
WebHeaderCollection aPIHeaderValues = new WebHeaderCollection();
aPIHeaderValues .Add("UserName","somevalue");
aPIHeaderValues .Add("TokenValue", "somevalue");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.add(aPIHeaderValues);
HttpWebResponse response = (HttpWebResponse)_request.GetResponse();
But in .Net Core there is no way to add headers to request.Headers collection. As well as we cannot add headers by defining new WebHeaderCollection
WebHeaderCollection aPIHeaderValues = new WebHeaderCollection();
Is there any alternative way to do this in .Net Core

The question is about HttpWebRequest, which is different than HttpClient.
Using HttpWebRequest, you simply assign to a header you want like this:
request.Headers["HeaderToken"] = "HeaderValue";
.NET core will create the header if it does not exist.

Here is an example:
SampleClass sampleClass= null;
using (HttpClient client = new HttpClient()){
client.DefaultRequestHeaders.Add("Authorization", "TOKEN");
var data = await client.GetAsync("MY_API_URL");
var jsonResponse = await data.Content.ReadAsStringAsync();
if (jsonResponse != null)
sampleClass= JsonConvert.DeserializeObject<SampleClass>(jsonResponse);
return sampleClass;
}

Related

NetCore 3.1 PostAsync CustomHeaders not working

I have several RESTful services that working with each other. In one scenario I want to post some data from one service to another service and I want to attach some information in Header of the request. I saw several cases to do this and in the end I came up with this workaround:
var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(3);
var httpRequestMessage = new HttpRequestMessage {
Method = HttpMethod.Post,
RequestUri = new Uri(service2Address),
Content = new StringContent(JsonConvert.SerializeObject(obj))
};
httpRequestMessage.Headers.Add("myCustomHeaderKey", "myCustomHeaderValue");
var response = await httpClient.SendAsync(httpRequestMessage);
var responseString = await response.Content.ReadAsStringAsync();
With these lines of code, a Post request sent, but in service2 when I want to get the headers from request, there is no sign of myCustomHeaderKey in headers collection. I inspect Request.Headers in Visual Studio Watch and even try to get custom header with Request.Headers["myCustomHeaderKey"]. So what's wrong here?
EDIT 1
This implementation in based on this tutorial.
I have developed code like yours. Have created Two Asp.net core 3.1 project with standart template. One service is starting localhost:44320 and other localhost:44300
localhost:44320/PostService wrote the your codes.
Then get this url with browser. localhost:44320/weatherforecast/IncomeService function is like below
Finally i put breakpoint to where get request header. Result is like below
There is a not a problem. Maybe you use change request header middleware. Or if you are using something like nginx. this problem maybe nginx configuration.

ASP.NET Core making SOAP API request with WCF client how to add a Cookie header to the request?

So I am currently working on making SOAP API request to a service with WCF generated code "Client object", I am wondering how to set the Cookie header to the request?
In general, we add the custom HTTP header by using HttpRequestMessageProperty. Please refer to the below code.
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
try
{
using (OperationContextScope ocs=new OperationContextScope(client.InnerChannel))
{
var requestProp = new HttpRequestMessageProperty();
requestProp.Headers["myhttpheader"] = "Boom";
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProp;
var result = client.SayHelloAsync();
Console.WriteLine(result.Result);
}
Result.
WebOperationContext is a convenience wrapper around the OperationContext. At present, it hasn’t been implemented yet in the Aspnet Core.
https://github.com/dotnet/wcf/issues/2686
Feel free to let me know if there is anything I can help with.

Api calling in .net core razor pages

I am working on (built-in web apis) provided by whatsapp business api. As a newbie in .net core razor pages and web apis. I want to know how can I get access to the body of the post request api. Take an example below for sending a message
Post: {URL}/v1/messages
Request Body:
"to": "",
"message_type:"
"message_text:"
"recipient_type: "individual | group""
How can I make a call to the builtin api and access the body parts of it?
Ofcourse, we as a developer can use postman for checking the working of api. But take this as a client and for the client we have some fields like
To:
Message:
How can take these fields and put it into the api call body and then when the user click on the send, the api call works and shows whatever we want to show the user for example a model with send successfully etc.
You can call the API using HttpClient.
Add the URL in await client.PostAsync() function. If you have authorization use client.DefaultRequestHeaders.Authorization otherwise omit it
string myContent = "";
string myJson = <JsonQuery>;
using (HttpClient client = new HttpClient())
{
// If any authorization available
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenLabel.Text.Trim());
using (HttpResponseMessage response = await client.PostAsync("https:url", new StringContent(myJson, Encoding.UTF8, "application/json")))
{
using (HttpContent content = response.Content)
{
myContent = await content.ReadAsStringAsync();
}
}
}
Update
Content
string myJson = "{\"subject\": }";
URL
using (HttpResponseMessage response = await client.PostAsync("{{URL}}/v1/groups", new StringContent(myJson, Encoding.UTF8, "application/json")))
Header
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "");

HttpRequestMessage.Content is null in receiving Controller action

I've looked at some similar posts, but all had some relevant detail that does not apply in my case. I have an existing Shopper service with a Register method. It is built on .NET Framework 4.6.1 Web API. I have a number of working scenarios in which another .NET Framework 4.6.1 Web API service calls the Shopper service using HttpClient and HttpRequestMessage. I do this with GET, PUT, and POST methods and successfully pass data to the PUT and POST methods using
request.Content = new ObjectContent<MemberAddress>(memberAddress, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
I'm now developing a new service, this one built on ASP.NET Core Web API. I'm attempting to call a POST action in the Shopper service. I'm getting my HttpClient from IHttpClientFactory.CreateClient. The HttpRequestMessage set up is, I think, the same as in my other calling services.
var request = new HttpRequestMessage(HttpMethod.Post, updateShopperUrl);
request.Content = new ObjectContent<MemberRegistration>(memberRegistration, new System.Net.Http.Formatting.JsonMediaTypeFormatter(), "application/json");
The call to the service looks like this:
var httpClient = _clientFactory.CreateClient();
var response = await httpClient.SendAsync(request);
I can inspect request.Content.Value before the call and it contains the object/data I expect. The controller action code on the other end looks like this:
[Route("{shopperId}/register")]
[Route("~/api/shopper/{shopperId}/register")]
[HttpPost]
public IHttpActionResult RegisterNewMember(string shopperId, [FromBody] MemberRegistration memberRegistration)
{
But the memberRegistration parameter is always null. The [FromBody] attribute is recent addition in an attempt to solve this problem, but it did not help. FromBody should be the default behavior for a complex object parameter anyway. I can POST to that endpoint with Postman and the memberRegistration data comes through.
Either I'm just missing something obvious or maybe there's something different happening in the ASP.NET Core calling side of the equation.
It appears you are trying to post JSON data
Try changing the approach a bit and see if it make a difference.
var json = JsonConvert.SerializeObject(memberRegistration);
var content = new StringContent(json, Encoding.UTF8,"application/json");
var httpClient = _clientFactory.CreateClient();
var response = await httpClient.PostAsync(updateShopperUrl, content);
The above manually serializes the object to JSON and Posts it to the web API.
It is possible there could have been an issue with the formatter used with the ObjectContent

Sharepoint 2013 REST api from desktop application - Authentication

I am trying to consume SharePoint 2013 REST services from a Desktop application ( cross-platform, cross-os ). Application is basically a HTML page in application view.
Is there a simple way I can authenticate my calls using HTTP methods ?
Yes, you can get authenticated and receive a digest via a REST call.
string url = "http://Your.SP.Site";
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
var response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
JsonObject val = JsonValue.Parse(content).GetObject();
JsonObject d = val.GetNamedObject("d");
JsonObject wi = d.GetNamedObject("GetContextWebInformation");
retVal = wi.GetNamedString("FormDigestValue");
}
The above example shows how to retrieve the digest in C# with the HttpClient. This string needs to be passed as a header to all of the other rest calls you make to carry forward the authentication. You can create a credential by passing in a username and password if needed.
I have more examples here:
https://arcandotnet.wordpress.com/2015/04/01/sharepoint-2013-rest-services-using-c-and-the-httpclient-for-windows-store-apps/
You can do these calls in JavaScript as well and Microsoft has a lot of documentation on that. There is also .NET library, Microsoft.SharePoint.Client.DLL (CSOM) that simplifies this type of coding but you must have the library installed on the client.