Ray Ray - 1 year ago 167
ASP.NET (C#) Question

How to set WebApi request header on server side

I'm trying to use MVC to call a WebApi method according to HTTP. I need to send some info every time, like userID and app version. How can I add this info to the header? I want to do it as an ajax call, not by client side code like it is now):

'beforeSend: function (req) {
req.setRequestHeader("Accept", "version=1.00,requestTime=" + new Date());

But on server side, I can't set RequestHeader with string
This is my server code:

HttpClient client = new HttpClient();
var request = new HttpRequestMessage()
RequestUri = new Uri("http://localhost/WebAPIDemo/FilterAttribute-MVC"),
Method = HttpMethod.Get,

//request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
List<OfficeSupply> os=new List<OfficeSupply>();
var task = client.SendAsync(request)
.ContinueWith((taskwithmsg) =>
var response = taskwithmsg.Result;

var jsonTask = response.Content.ReadAsAsync<List<OfficeSupply>>();
var jsonObject = jsonTask.Result;
os = jsonObject.ToList();

needs to be a 'MediaTypeWithQualityHeaderValue' type value,but I just want to set it to custom, like the ajax call. How should I do it?

Also, I want to change Header Authorization parameter, but this code:

'client.DefaultRequestHeaders.Add("Authorization", "12345");'

did not work and


told me it is read-only.

How do I set it on the server side before sending?

Answer Source

You can specify a custom auth scheme by doing something like,

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("scheme","whatever parameters");

You can set a completely custom header with code like this:

request.Headers.TryAddWithoutValidation("foo", new List<string>() {"sdadads"});

Be careful though, the accept header example you showed above is completely invalid. There are very precise rules as to how the contents of an accept header should be formatted and your example is not valid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download