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?