Reputation: 1188
I am working on ASP.NET Core 2.1 Web API project. I am trying to follow this article: https://www.c-sharpcorner.com/article/jwt-json-web-token-authentication-in-asp-net-core/ but I am stuck at Action. My model class just won't bind to the input.
[AllowAnonymous]
[HttpPost]
public IActionResult Login([FromBody] LoginVM loginVM)
{
IActionResult response = Unauthorized(); // cant reach this point, my breakpoint is here
var user = AuthenticateUser(new UserModel { });
if (user != null)
{
var tokenString = GenerateJSONWebToken(user);
response = Ok(new { token = tokenString });
}
return response;
}
public class LoginVM
{
public string Username { get; set; }
public string Password { get; set; }
}
Upvotes: 6
Views: 4526
Reputation: 239220
You're posting as x-www-form-urlencoded
, but you have the [FromBody]
attribute applied to the action param. These two things are fundamentally incompatible. To accept x-www-form-urlencoded
(or multipart/form-data
) you must apply the [FromForm]
attribute to the param. If you have [FromBody]
, as you do now, then you can only accept something like application/json
or application/xml
(if you also enable the XML serializers).
If the issue is that you want to be able to accept both application/json
and x-www-form-urlencoded
request bodies, that is not possible. You'll need a separate action for each request body encoding, though you can factor out the actual meat of the action into a private method on the controller that both actions can utilize.
Upvotes: 3
Reputation: 56
Choose "raw" in Body and "Content-Type" as "application/json" in postman and then try.
Upvotes: 0