1

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(***);
        //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>>();
                jsonTask.Wait();
                var jsonObject = jsonTask.Result;
                os = jsonObject.ToList();
            });
        task.Wait();

*** 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

  request.Headers.Authorization.Parameter

told me it is read-only.

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi!I've tried your code, but it doesn't show on chrome request headers(F12 Network Headers),everything has not changed
How would Chrome be able to see the request if it is coming from a httpClient request? Use fiddler to see the request.
Fiddler request headers only has:four accept param and a user agent?
0

I used to follow the below approach to set request header. Please try it if works for you.

[Script]

 $("#Grid1").ajaxSuccess(function (evt, request, settings) {
    $('.Status').html(request.getResponseHeader("Status"));
  });

[View]

  <h2>Status:</h2><h2 class="Status" style="color:Red;">

[Controller]

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save(Order orders)
    {
        string status = string.Empty;

        if (orders != null)
        {
            OrderRepository.Update(orders);
            status = "Updated";
        }

        Response.AddHeader("Status", status);            
        return data.GridActions<EditableOrder>();
    }

Response header

3 Comments

Sorry,I want to set request header,not the response,and for webapi,I need use HttpClient and HttpRequestMessage to send request,I just don't know how to set the object's property properly,by the way,which tool do you used to get the header?browser?
It is 'firebug' developer addon in Firefox browser.
@Ray You don't need to use HttpClient to call Web API, you can use any software that can make a http request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.