【问题标题】:Asp .NET Web Api + MVC + Angular 2 - action with two parametersAsp .NET Web Api + MVC + Angular 2 - 带有两个参数的操作
【发布时间】:2018-03-14 12:35:59
【问题描述】:

我有一个带有 Angular 2 的 ASP .NET MVC 应用程序。我添加了一个 WebApi 控制器并尝试从 Angular 服务与它进行通信,但它没有使用两个参数访问 WebApi 控制器中的操作。

我想我已经阅读了有关这件事的所有问题。我在 MVC 路由之前注册了我的 webApi 路由。如果不需要任何参数,我可以访问该操作。但是,如果我尝试使用参数来访问它,我会不断收到 404 not found for the Login 操作 - POST localhost:12312/api/userapi/login 404 (Not Found)。

我尝试了 WebApiConfig 的各种格式 - 使用可选参数,不使用它们,使用动态控制器占位符,以及动作和控制器的确切名称等。我也试过路由属性,但没有效果。

我尝试将其作为单参数“对象凭据”并修改了WebApiConfig.cs,但结果没有改变。

RouteConfig.cs

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

WebApiConfig.cs

       config.MapHttpAttributeRoutes();

       config.Routes.MapHttpRoute(
            name: "api",
            routeTemplate: "api/userapi/login/{username}/{password}",
            defaults: new { username = RouteParameter.Optional, password = 
            RouteParameter.Optional }
        );

       config.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "api/{controller}/{action}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );

UserApiController.cs

    [HttpPost]
    public HttpResponseMessage LogIn(string username, string password)
    {
        return ToJson(userRep.LogIn(username, password));
    }

角度

this.http.post(url, JSON.stringify(credentials), { headers: headers })
            .subscribe(res => {
                resolve(res.json());
            }, (err) => {
                reject(err);
            });

【问题讨论】:

    标签: c# asp.net-mvc angular asp.net-web-api routing


    【解决方案1】:

    我不确定为什么它不能以你的方式工作(使用 parmas),但我会简单地创建一个类似的模型

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

    然后在登录方法中

     [HttpPost]
        public HttpResponseMessage LogIn(LoginModel model)
        {
            return ToJson(userRep.LogIn(model.username, model.password));
        }
    

    不需要自定义路由,只需使用默认配置即可

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      相关资源
      最近更新 更多