Rod
Rod

Reputation: 752

Simple POST with Web Api .NET Core

I can't produce my code despite the different questions and answers found on stackoverflow.

Here is my problem, I want to receive the Username and Password of the client to perform the verification (the equality is only for the example).

However the LoginPost variable is all the time null. Furthermore I have difficulty understanding the best way to send the client an http code and json at the same time.

using Microsoft.AspNetCore.Mvc;
using web.Models;

namespace web.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class LoginController : ControllerBase
    {
        [HttpPost]
        public ActionResult<LoginPost> LoginPost([FromBody] LoginPost loginPost)
        {
            // (1) FAIL, loginPost variable is null

            if (loginPost.Username == loginPost.Password)
            {
                return loginPost;
            }


            // (2) How to add a message like "User/Password fails"

            return Unauthorized(); 
        }

    }
}

Note the annotations (1) and (2) in the code.

Here's the jQuery code

$.ajax({
        url: '../api/Login',
        type: 'POST',
        dataType: "json",
        contentType: "application/json, charset=utf-8",
        data: {
            Username: username,
            Password: password
        },
        statusCode: {
            200: function (data) {
                console.log(data);
            }
            401: function (data) {
                console.log(data);
            }
            500: function (data) {
                console.log(data);
            }
        }
});

and LoginPost.cs class:

public class LoginPost
{
    public string Username { get; set; }
    public string Password { get; set; }
}

Upvotes: 1

Views: 3473

Answers (3)

Mike
Mike

Reputation: 3015

Since you don't seem to want to use json, post the data as a form.

Remove contentType: "application/json, charset=utf-8", from your ajax call.

'application/x-www-form-urlencoded; charset=UTF-8' is the default so the data will be sent as a form. Also remove [FromBody] Attribute and it should work

Upvotes: 3

Marius
Marius

Reputation: 1679

The login controller is working fine, I tested it with Postman. The problem lies with the ajax call: it does not send the data as the body of the POST request but as URL query parameters (i.e. Username=username&Password=password).

To send the data in the body of the POST request you need to send the data as json string:

data: JSON.stringify({
    "Username": "username",
    "Password": "password"
}),

Upvotes: 1

Amin Mozhgani
Amin Mozhgani

Reputation: 604

For (2) question, you can return status code :

return StatusCode(401, "User/Password fails");

Upvotes: 1

Related Questions