Ray
Ray

Reputation: 127

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(***);
        //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?

Upvotes: 1

Views: 7680

Answers (2)

RGR
RGR

Reputation: 1571

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

Upvotes: 0

Darrel Miller
Darrel Miller

Reputation: 142252

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.

Upvotes: 2

Related Questions