Kris Bonev Kris Bonev - 8 months ago 134
C# Question

Asp .NET Web Api + MVC + Angular 2 - action with two parameters

I have an ASP .NET MVC application with Angular 2. I added a WebApi Controller and try to communicate from angular service with it, but it does not access an action within the WebApi Controller with two parameters.

I think I read all the question regarding that matter. I have my webApi routes registered before the MVC ones. I can access the action, if it does not require any parameters. But if I try to hit it with the parameters I keep getting 404 not found for the Login action - POST localhost:12312/api/userapi/login 404 (Not Found).

I tried every kind of formatting for the WebApiConfig - with optional parameters, without them, with dynamic controller placeholders, with the exact names for action and controller,etc. I tried Routing attribute as well, but with no effect.

I tried to put it as a single parameter "object credentials" and modified the WebApiConfig.cs as well, but the result didn't change.



name: "Default",
url: "{*anything}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }



name: "api",
routeTemplate: "api/userapi/login/{username}/{password}",
defaults: new { username = RouteParameter.Optional, password =
RouteParameter.Optional }

name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }


public HttpResponseMessage LogIn(string username, string password)
return ToJson(userRep.LogIn(username, password));

angular, JSON.stringify(credentials), { headers: headers })
.subscribe(res => {
}, (err) => {

Answer Source

Am not sure why its not working in your way(using parmas) but i will simply create an model something like

public class LoginModel{
    public UserName {get;set;}
    public Password {get;set;}

then in login mathod

    public HttpResponseMessage LogIn(LoginModel model)
        return ToJson(userRep.LogIn(model.username, model.password));

No need of custom routing just use default config

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download