首页 > 解决方案 > 制作 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 来发送标头?

标签: jqueryasp.net-core

解决方案


尝试使用 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)
   }
});

我希望这对你有用。


推荐阅读