Reputation: 71
I need to pass information from client and MVC through Request globally for any Web API calls that was made from MVC and UI.
I use HttpClient to make WebApi calls.
I use Middleware from MVC to intercept the Web API calls to add some custom headers in the Request as shown below. Below is my sample code.
public async Task Invoke(HttpContext context)
{
context.Request.Headers.Add("AuditInfo", "xxxxxxxxxx");
await next.Invoke(context);
}
When I check the request headers from WebApi, I am not able to see headers that I added in the Middleware.
Note : I am able to add the headers successfully and view it from WebApi Request, if I add the headers while creating HttpClient as shown below. But I want to add this functionality globally for the Web API request that’s been made from MVC and UI.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("AuditInfo", "xxxxxxxxxx");
client.BaseAddress = new Uri("http://localhost:62239/");
HttpResponseMessage response = client.GetAsync("api/test/").Result;
if (response.IsSuccessStatusCode) string jsonResponse = response.Content.ReadAsStringAsync().Result;
Upvotes: 0
Views: 517
Reputation: 24103
If i understand you correctly, you want to use middleware in mvc application to handle HttpClient
. Middleware is for handling incoming requests, not outgoing requests. Since HttpClient
request is a outgoing request you can't use middleware to handle it.
But I want to add this functionality globally for the Web API request
You can simply create a HttpClient
factory class for this:
public interface IHttpClientFactory
{
HttpClient GetClient();
}
public class HttpClientFactory : IHttpClientFactory
{
public HttpClient GetClient()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("AuditInfo", "xxxxxxxxxx");
client.BaseAddress = new Uri("http://localhost:62239/");
return client;
}
}
And then whenever you need get and use it:
private readonly IHttpClientFactory _httpClientFactory;
....
var client = _httpClientFactory.GetClient();
HttpResponseMessage response = client.GetAsync("api/test/").Result;
if (response.IsSuccessStatusCode) string jsonResponse = response.Content.ReadAsStringAsync().Result;
Upvotes: 0