简体   繁体   中英

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

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' '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

对于(2)问题,您可以返回状态代码:

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

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 (ie 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"
}),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM