简体   繁体   中英

Razor page POST handler not receiving JSON data from jQuery AJAX

I'm sending a POST request to a Razor page handler using jQuery .ajax() . The network tab shows that this data is being sent as expected:

请求有效载荷

My breakpoints confirm that I'm hitting the handler, though the invitationId is not coming over (or at the very least, not deserializing correctly):

处理程序

The JavaScript is as follows:

class GenericService {
  constructor(controller) {
    this.controller = controller;
  }

  async post(data, handler = "") {
    return await $.ajax({
      type: "post",
      beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
      },
      data: JSON.stringify(data),
      url: `/${this.controller}${handler}`,
      contentType: "application/json",
      dataType: "json"
    });
  }
}
(async () => {
  const _ajax = new GenericService("Admin/Index");
  await _ajax.post({ invitationId: 1 }, "Reset");
})();

I imagine that I'm misunderstanding the implicit deserialization, but examples I've seen elsewhere on the internet seem to indicate that sending a JSON serialized object should be fine.

This is using .NET Core 3.0.

Can anyone explain what might be my issue here?

As expected, I had some wires crossed as it relates to the deserialization.

If I send the data as a plain object without serialization (and remove the corresponding json type declarations from the .ajax() options), the invitationId comes across.

return await $.ajax({
  type: "post",
  beforeSend: function (xhr) {
    xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
  },
  data: data,                            //Remove JSON.stringify(...)
  url: `/${this.controller}${handler}`
  //contentType: "application/json",       Remove
  //dataType: "json"                       Remove
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM