Skip to content
Advertisement

Values are null when POSTing to Razor Handler via JavaScript fetch()

I’m trying to POST email content to a Razor Handler, but the request values don’t seem to be properly binding. I’ve been scouring all I can (including many questions on SO) for answers without luck.

The code sends the data properly as best I can tell from the Network tab. My breakpoint in the handler is hit, but the request has null values. (I’m running .NET Core 3.0, for what it’s worth.)

I’ve tried:

  • adding Content-Type to the fetch headers
  • adding the [FromBody] attribute to the request parameter
  • sending the body as an object instead of serializing it
  • changing List<int> to int[]
  • changing my request class properties to be lowercase, camelcase, etc, just incase there was a different ContractResolver in my default SerializerSettings

My code and some screenshots are below. Any suggestions/answers appreciated.

JS

//sample data
const To = "stack@overflow.com";
const Body = "This is the email body.";
const Subject = "Hello world!";
const PortraitId = 17;
const FileIds = [1,2,3];
const body = { PortraitId, To, Subject, Body, FileIds };

const handler = "SendEmail";
const url = new URL(window.location.href.split('?')[0]);
const parameters = { handler };
url.search = new URLSearchParams(parameters).toString();

await fetch(url, {
  method: "POST",
  body: JSON.stringify(body),
  headers: {
    "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
  }
});

C#

public class SendEmailRequest
{
  public int PortraitId { get; set; }
  public string To { get; set; }
  public string Subject { get; set; }
  public string Body { get; set; }
  public List<int> FileIds { get; set; }
}
public async Task<IActionResult> OnPostSendEmail(SendEmailRequest request) {
  //do stuff
}

enter image description here

enter image description here

enter image description here

Advertisement

Answer

Ok, so I replicated that, added both [FromBody] and "Content-Type": "application/json"

([FromBody] SendEmailRequest request)

and

headers: {
   "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val(),
   "Content-Type": "application/json"
}

And this started working properly. So if with these fixes it won’t work, please to share all your Middlewares (or Authentication providers).

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement