0

I have an api in asp.net core which is:

[HttpPost]
public IActionResult Post([FromBody] Reservation res)
{
    StringValues key = Request.Headers["Key"]; // no header when making jquery .ajax() call


    return Ok(repository.AddReservation(new Reservation
    {
        Name = res.Name,
        StartLocation = res.StartLocation,
        EndLocation = res.EndLocation
    }));
}

To this API I am making API call with jQuery AJAX() method like this:

$.ajax({
    url: "http://localhost:8888/api/Reservation",
    headers: {
        Key: "Key",
        Secret: "Secret@123"
    },
    method: "post",
    contentType: "application/json",
    data: JSON.stringify({
        Id: 0,
        Name: $("#Name").val(),
        StartLocation: $("#StartLocation").val(),
        EndLocation: $("#EndLocation").val()
    }),
    success: function (result, status, xhr) {
        console.log(result);
    },
    error: function (xhr, status, error) {
        console.log(xhr)
    }
});

The problem is that the headers are not sent to the API because My breakpoint on this line StringValues key = Request.Headers["Key"]; does not gets any header value why?

I also want to tell you that the data parameter values from .ajax() are received by my API but not header values, Please help?

I am able to send the Headers easily by making API call through an ASP.NET MVC application but not with jQuery. The code that is working is:

[HttpPost]
public async Task<IActionResult> AddReservation(Reservation reservation)
{
    Reservation receivedReservation = new Reservation();
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("Key", "Secret@123");
        StringContent content = new StringContent(JsonConvert.SerializeObject(reservation), Encoding.UTF8, "application/json");

        using (var response = await httpClient.PostAsync("http://localhost:8888/api/Reservation", content))
        {
            string apiResponse = await response.Content.ReadAsStringAsync();
            try
            {
                receivedReservation = JsonConvert.DeserializeObject<Reservation>(apiResponse);
            }
            catch(Exception ex)
            {
                ViewBag.Result = apiResponse;
                return View();
            }
        }
    }
    return View(receivedReservation);
}

Please tell me why jQuery is not able to sent headers with making api call?

3
  • Are you using jquery 1.5+? Headers was added in 1.5 Commented Feb 13, 2019 at 11:36
  • @BlackICE i am using much newer version - v3.3.1. Commented Feb 13, 2019 at 11:38
  • Is there any demo to reproduce your issue? I fail to reproduce it with .net core and jquery v3.3.1. Press F12 in the browser to check the Network tab to see whether the request sent headers correctly. Commented Feb 14, 2019 at 3:28

2 Answers 2

1

Try sending the headers using beforeSend method and setRequestHeader method:

$.ajax({
   url: "http://localhost:8888/api/Reservation",
   beforeSend: function(request) {
      request.setRequestHeader("Key", "Key");
      request.setRequestHeader("Secret", "Secret@123");
   },
   method: "post",
   contentType: "application/json",
   data: JSON.stringify({
       Id: 0,
       Name: $("#Name").val(),
       StartLocation: $("#StartLocation").val(),
       EndLocation: $("#EndLocation").val()
   }),
   success: function (result, status, xhr) {
       console.log(result);
   },
   error: function (xhr, status, error) {
       console.log(xhr)
   }
});

I hope this works for you.

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

Comments

0

I solved it by setting the headers as shown below during making the ajax call:

headers: {
    Key: "Secret@123"
},

1 Comment

Good for you. Please set your answer as an accepted one so that the question status change to solved (answered)

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.