DanilGholtsman
DanilGholtsman

Reputation: 2374

All variables are null at the request with Axios to ASP.Net Core Controller

Here is my client request code:

import request from 'axios';

//...

     let url = 'Login/SignIn',
                headers = {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                },
                data = JSON.stringify( {
                    name: 'danil',
                    password: 'pwd'
                });

     request.post(url, data, headers);

looks fine by the first glance.

Request is pending here: enter image description here

But it all ended up like that in my controller:

enter image description here

Here's the code btw:

[HttpPost]
        public async Task<ActionResult> SignIn([FromBody]string name, [FromBody]string password)
        {

            var userLoginCommand = new UserLogInCommand {
                Login = name,
                Password = password
            };

            await _dispatcher.DispatchAsync(userLoginCommand);
            return Content(userLoginCommand.Result, "application/json");
        }

Whats wrong with it? What did I forgot?

I tried to play around with JSON.stringify by adding it and removing, tried to not sending headers (and then it throws 415 error) but no changes there. Still got nulls.

UPD: As Ali suggested in comments, passing data is goes fine if we use LoginModel for this like that:

 public class LoginModel
        {
            public string name { get; set; }
            public string password { get; set; }
        }

enter image description here

But why it's not going work just like that in a simple way?

Upvotes: 5

Views: 3302

Answers (1)

Daniel Matac
Daniel Matac

Reputation: 301

Only one parameter is allowed to read from the message body. In your example you have two parameters with FromBody attribute, that's why you have null values.

Please find documentation here: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

"At most one parameter is allowed to read from the message body."

Upvotes: 1

Related Questions