how i can return the header content from webapi to AngularJS $http service - asp.net-web-api2

I want to return the content headers from webapi as
httpResponseMessage.Content = new ByteArrayContent(bytes.ToArray());
httpResponseMessage.Content.Headers.Add("x-filename", fileName);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
and i want to return this content headers to angularjs $http service as
$http.get(...).then(function(response){..})
i am using AngularJS 1.6, but previous in AngularJS 1.3, it is working fine , by using
$http.get(...).success
but as now it is AngularJS 1.6, it is not working, i cannot work with angularjs 1.3 in my project as it is already 1.6 is there, so please help me, how to get the content header data from webapi to angularjs $http service

Is it a cross-domain request? If yes, have you tried exposing custom headers?
httpResponseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "x-filename");

Related

Heasers needed by spring security to consume api

I developped an api using spring boot withuser authentication and authorizations with spring securtiy.
And I am using spring security login form for user authentication.
I tested it with postman and it is working perfectly.
But when I implemented the api in asp.net mvc 5 project the login works and return the connected user but i get unauthorized message after any other request that needs authenticated user.
I think it works in postman because he generates or get headers from response of login.
How can i get them so i can integrate them in other requests.
Edit:
It seems that JSESSIONID Cookie header is needed and I took it from login response header and added it to my request header but it still doesn't work
Here is my code that adds the header:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Cookie", loginResponse.Headers.GetValues("Set-Cookie").First().Split(';')[0].Trim());
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
client.BaseAddress = new Uri("http://localhost:8080/api/");
HttpResponseMessage response = client.GetAsync("customer/users").Result;
This line give me the Cookie header value from login response i need:
loginResponse.Headers.GetValues("Set-Cookie").First().Split(';')[0].Trim()
HttpClient will ignore header Cookie
when creating an instance to it you need to pass an HttpClientHandler with UseCookies to false so it will not ignore it
HttpClient httpClient = new HttpClient(new HttpClientHandler { UseCookies = false })
Answer found here

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.

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

How to add Header values to HttpWebRequest in .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;
}