Reputation: 3456
I am trying to access my login method on server side. I do this with an ajax call but it does not work when I do it with a post.
Code:
$(".getToken").on("click", function () {
$.ajax({
url: "api/Login",
type: 'POST',
data: { username: "myusername", password : "mypass!" },
contentType: 'application/json; charset=utf-8',
success: function (data) {
//logic
},
error: function (event, jqxhr, settings, thrownError) {
var h;
}
});
})
Server:
[AllowAnonymous, HttpPost, Route("api/Login")]
public IHttpActionResult Login(string username, string password)
{ // some logic}
Routconfig:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Login",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Login", userName = UrlParameter.Optional, password = UrlParameter.Optional }
);
IT WORKS when i change from POST to GET. Error message:
No HTTP resource was found that matches the request URI 'http://localhost:64251/api/Login'
What am I doing wrong?
Upvotes: 0
Views: 146
Reputation: 1000
Instead of passing the parameters as strings, create a Model that represents them and pass that up.
public class UserLoginModel {
public string UserName {get;set;}
public string Password {get;set;}
}
The data your javascript provides will have to match that model exactly, so it will need a UserName property and a Password property. Then you can change the signature of your Action to
public IHttpActionResult Login(UserLoginModel login)
I don't believe .net MVC routing natively parses strings from the body of a request to separate in to parameters. If you provide it with an object, it can easily deserialize your json to a specific type.
Also, you don't need to have multiple routes configured the way you do. One route with the pattern "{controller}/{action}/{id}" will work just fine.
Upvotes: 2