【发布时间】:2016-09-13 21:32:38
【问题描述】:
我在将参数传递给我的 web api 时遇到了很大的困难。
有两种情况,我将它们都列出来。
-
我想在下面传递一个简单的字符串参数
[HttpGet] public string VerifyName(string name) { return name + "hi"; }
为此,我在我的 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."}
- 同样,当我尝试传递一个对象时,它会给出相同的结果
我的角度函数
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;
});
Web 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 }
);
}
我认为基本的路由存在一些问题,但有些无法弄清楚它是什么,请提出建议
【问题讨论】:
-
最好将复杂对象发布到 API
-
首先注意到您没有提到路径的基本 url 完整 url 它应该包括
localhost以及 -
对于第一个示例,如果您将控制器方法更改为接受并使用
id参数而不是name,然后您可以将您的角度调用修改为$http.get('/api/VisitorWeb/VerifyName/' + name),它应该可以工作。正如其他人指出的那样,get 不接受对象。
标签: c# angularjs http-status-code-404 asp.net-web-api2