jquery - 制作 jquery .ajax() 方法时,标头值未发送到 ASP.NET Core API
问题描述
我在 asp.net 核心中有一个 api,它是:
[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
}));
}
对于这个 API,我使用 jQuery AJAX() 方法进行 API 调用,如下所示:
$.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)
}
});
问题是标头没有发送到 API,因为我在这一行上的断点StringValues key = Request.Headers["Key"];
没有获得任何标头值,为什么?
我还想告诉您,来自 .ajax() 的数据参数值由我的 API 接收,但不是标头值,请帮忙?
我可以通过 ASP.NET MVC 应用程序而不是 jQuery 进行 API 调用来轻松发送标头。正在运行的代码是:
[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);
}
请告诉我为什么 jQuery 无法通过调用 api 来发送标头?
解决方案
尝试使用 beforeSend 方法和 setRequestHeader 方法发送标头:
$.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)
}
});
我希望这对你有用。
推荐阅读
- c++ - 如何为每个函数调用生成新的模板类型?
- macos - 从非沙盒应用程序通过 DOMAIN 套接字连接到 MacOS 沙盒应用程序
- javascript - 相同的计算从对象内部返回 NaN 但从执行相同计算的函数返回整数
- javascript - 移动设备上的 Web Audio API 问题(似乎无法调试问题)
- hybris - 如何使用具有复合键的集合进行 Impex?
- php - Heroku PHP & Apache dyno 崩溃并出现错误 H10
- node.js - nodejs axios获取请求响应正文被截断/不完整的curl作品
- ansible - 如何在 Ansible playbook 中将 shell 函数作为命令运行?
- vim - 如何在vim中折叠光标后的空间
- javascript - javascript中字符串开头和结尾的+是什么意思?