Home > Enterprise >  Web API AJAX doesn't map to DTO
Web API AJAX doesn't map to DTO

Time:07-05

Model:

public class LoginToken
{
    public string Username { get; set; }

    public string Password { get; set; }
}

AJAX

$.ajax({
    contentType:"application/json",
    url: "/api/Admin/Login",
    method: "GET",
    dataType: "json",
    data:{
        "Username":"random",
        "Password":"random"
    },
    success: function (data){
       //not important
    },
    error:function(data){
        //not important
    }
})

API Controller

[HttpGet]
    public string Login(LoginToken token)
    {
        //not important
    }

I've tried using JSON.stringify, I tried encapsulating data inside javascript inside an object called token, I tried the same thing but with stringify and the data doesn't map to DTO. Essentially token is always null. When I do an API call using Postman with simple

{
  "Username":"random",
  "Password":"random"
}

it maps the data perfectly.

Edit: Also adding [FromBody] in front of the object parameter doesn't solve it. Also I noticed that if I put parameters outside of the data object like this

[HttpGet]
public string Login(string username, string password)
{
    //not important
}  

It would map to the username and password.

CodePudding user response:

you can not use GET with contentType:"application/json", so you have to fix your ajax type to post type (not method), and since you are using json, data should be stringified

 ...
 type: 'POST',
 contentType: 'application/json; charset=utf-8',
 data: JSON.stringify({
        "Username":"random",
        "Password":"random"
    }),
....

and add frombody to an action

    [HttpPost]
    public string Login([FromBody]LoginToken token)
    {
        //not important
    }

but if you still want to use Get as it is , you only need to remove contentType:"application/json" from your ajax

$.ajax({
   
    url: "/api/Admin/Login",
    type: "GET",
    dataType: "json",
    data:{
        "Username":"random",
        "Password":"random"
    },
    success: function (data){
    .....
  • Related