6

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; }
}

enter image description here

6
  • So what is inside // some code? Are you sure it's not that giving you the error? Commented Jul 23, 2019 at 15:20
  • @DavidG I am unable to reach the breakpoint which is at first line in the method. Commented Jul 23, 2019 at 15:20
  • 2
    Can you add your main class declaration too? i'm assuming you've copied the [Route("api/[controller]")] and the [ApiController] too Commented Jul 23, 2019 at 15:27
  • @Sasha yes I did that but I have checked by placing break point in the constructor of the class, that point is reachable so I think routing is fine here. Commented Jul 23, 2019 at 15:28
  • 1
    Use [FromForm]. Reference Model Binding in ASP.NET Core Commented Jul 23, 2019 at 15:29

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Choose "raw" in Body and "Content-Type" as "application/json" in postman and then try.

1 Comment

Welcome to StackOverflow. See the comments attached to the question. Try to explain more clearly why this is an answer to the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.