2016-05-17 58 views
0

我在向我的web api传递参数时很挣扎。如何通过angularjs在Web api中传递多种类型的参数?

有两种情况我会列出他们两个。

  1. 我想通过以下

    [HttpGet] 
        public string VerifyName(string name) 
        { 
    
         return name + "hi"; 
        } 
    

一个简单的字符串PARAM这样对于那些我在我的angularjs控制器创建这样一个URL。

var name = "hello"; 
      var msg = ""; 
      $http.get('/api/VisitorWeb/VerifyName', name).success(function (data) { 
       msg = data; 
      }).error(function (data) { 
       $scope.error = "An error has occured while adding! " + data; 
      }); 

这使返回404还

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:43516/api/VisitorWeb/VerifyName'.","MessageDetail":"No action was found on the controller 'VisitorWeb' that matches the request."} 
  1. 同样,当我试图传递一个对象时,它被赋予了相同的结果

我的角度功能

var loginModel = { 
      UserName: $scope.UserName, 
      PassWord: $scope.Password 
     }; 

     var msg = ""; 
     $http.get('/api/VisitorWeb/VerifyLogin', loginModel).success(function (data) { 
      msg = data; 
     }).error(function (data) { 
      $scope.error = "An error has occured while adding! " + data; 
     }); 

网络API方法

[HttpGet] 
    public string VerifyLogin(UserLoginDomainModel loginModel) 
    { 
     //do some business logic 
     return "abc "; 
    } 

响应是404

WebApiConfig

public static void Register(HttpConfiguration config) 
     { 


config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 

     config.MapHttpAttributeRoutes(); 

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

我想有一些问题,这是基本的路由,但一些如何不能弄清楚它是什么,请建议

+0

最好将POST复杂对象发布到API – dbugger

+0

首先注意到你没有提到你的路径的基础url完整url它应该包括'localhost'以及 –

+0

http://stackoverflow.com/questions/19049989/web-api- get-method-with-complex-object-as-parameter – dbugger

回答

-2

试试看:

$http({ method: "GET", url: "/api/VisitorWeb/VerifyName", params: { name: name} }).success() 
+0

它不工作,得到相同的错误 – ankur

1

这个动作:

[HttpGet] 
public string VerifyName(string name) 
{ 
    return name + "hi"; 
} 

无属性的路由映射到路由到以下网址的标准约定定义:

http://yourhost/apiVisitorWeb/VerifyName?name=myNameValue 

因为你的路径模板"api/{controller}/{action}/{id}"需要名为id参数(不name)成为URI的一部分。

如果你想用你的路由作为或者是用来保持上述URI或更改参数的名称为id,所以你应该能够使用此地址:

http://yourhost/apiVisitorWeb/VerifyName/myNameValue 

同样的道理也适用复制到您的复杂类型参数中:在GET操作中,任何复杂参数都应该作为查询字符串参数的集合从URI绑定。您的第二个操作将绑定到以下URI:

http://yourhost/apiVisitorWeb/VerifyLogin?UserName=userNameValue&PassWord=myPassword 

但是,由于很多原因(顶部的安全性),这是一个不好的做法。我强烈建议您将这种操作转换为POST操作,以便您可以将模型作为请求的主体发送。