Jonty Morris
Jonty Morris

Reputation: 807

Why are POST params always null in .NET Core API

I've created a simple .NET core controller and am trying to query it from Angular.

The problem is that whenever I send a post request to my login action, I always receive null parameters! The weird thing though is that upon investigating, the request body/payload clearly shows my parameters are set.

See my screenshot for an example of what I mean. enter image description here

I have tried my best and have been reading through similar problems for the past few hours, but haven't had any success 😭

So my question is: What is causing my null parameters? .NET core must be doing something that I'm not aware of.

If you think seeing more code or the entire project would help, don't hesitate to ask!

Upvotes: 3

Views: 597

Answers (2)

jasonvuriker
jasonvuriker

Reputation: 275

I suggest to create class with properties email and password.And using [FromBody] attribute.

public class LoginModel
{
   public string Email {get;set;}
   public string Password {get;set}
}

[HttpPost]
[Route("login")
public async Task<IActionResult> Login([FromBody] LoginModel model)
{
  // your code
}

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68665

You can't get two separate parameters from body, cause it is going to bind email and password as properties of the parameter, not exact parameters. You need to create an object, which defines properties with those names, and use that object in the parameter

class Login 
{
   public string Email { get; set; }
   public string Password { get; set; }
}

In the action method parameter

([FromBody]Login model)

Upvotes: 3

Related Questions