Angularjs 如何在webapi中调用多个get方法
嗨,我正在用angularjs开发web api应用程序。我在一个控制器中有三个方法,但没有一个在调用。比如说,Angularjs 如何在webapi中调用多个get方法,angularjs,asp.net-web-api,routing,Angularjs,Asp.net Web Api,Routing,嗨,我正在用angularjs开发web api应用程序。我在一个控制器中有三个方法,但没有一个在调用。比如说, public class usersController : ApiController { //First Get method. [HttpGet] [SuperAdmin] [LoginCheck] [ActionName("me")] public HttpRespons
public class usersController : ApiController
{
//First Get method.
[HttpGet]
[SuperAdmin]
[LoginCheck]
[ActionName("me")]
public HttpResponseMessage me()
{
}
//second Get method.
[LoginCheck]
[SuperAdmin]
public IHttpActionResult Get(int id)
{
}
//third Get method.
[HttpGet]
[LoginCheck]
[SuperAdmin]
public HttpResponseMessage Get(string role)
{
}
我用下面的代码打电话
this.getSubs = function () {
var role = "SUPER_ADMIN";
//role is optional here
var url = '/api/users/' + role;
return $http.get(url).then(function (response) {
return response.data;
});
}
this.getcurrentuser = function () {
var url = '/api/users/me/';
return $http.get(url).then(function (response) {
return response.data;
});
}
this.getSubsbyID = function (id) {
var url = '/api/users/' + id;
return $http.get(url).then(function (response) {
return response.data;
});
}
我的路线如下
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我无法使用angularjs调用三个方法中的任何一个。我可以知道我哪里做错了吗?任何帮助都将不胜感激。谢谢两件事一是,您的请求作为CORS请求可能会有问题。您可能需要启用CORS。首先,您需要安装nuget软件包Microsoft.AspNet.WebApi.Cors,然后在路由调用之前将其添加到api配置文件中
config.EnableCors();
其次,将路由调整为使用属性路由可能会有所帮助。WebApi不像普通MVC控制器那样支持操作路由。您可能已经在配置文件中设置了一些路由,例如
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
这将允许您调用控制器用户,但我发现,试图让ApicController使用签名调用适当的get方法是有问题的。我建议您使用属性路由。如果还没有,您可以将属性路由添加到配置中
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
然后可以像这样设置HttpGet属性路由
public class usersController : ApiController
{
//First Get method.
[HttpGet]
[SuperAdmin]
[LoginCheck]
[Route("api/users/me")] // this is your routing attribute
public HttpResponseMessage me()
{
}
//second Get method.
[LoginCheck]
[SuperAdmin]
[Route("api/users/{id:int}")]
public IHttpActionResult Get(int id)
{
}
//third Get method.
[HttpGet]
[LoginCheck]
[SuperAdmin]
[Route("api/users/{role}")]
public HttpResponseMessage Get(string role)
{
}
希望这能有所帮助。您能发布实现这些方法的服务或控制器吗?这个问题可能有很多原因,请提供更多信息。如果您认为是路由问题,请张贴您的路由以及谢谢。加载资源失败:服务器以400错误请求的状态响应。您是否使用apache或nginx之类的代理服务器?否,我正在本地主机上运行。谢谢。我在页面加载时调用了三个API。在页面加载3次时,我点击了下面相同的url。[Routeapi/users/{role}]公共HttpResponseMessage Getstring roleDid更新路由配置并添加config.MapHttpAttribute路由;除非那条线在那里,否则这条[路线]是行不通的。这也需要在任何其他路由之前,但在config.EnableCors之后;如果你使用的是我启用的corsCors,没问题。config.maphttpAttribute路由;对不起,我忘了包括int约束通知[Routeapi/users/{id:int}]