led*_*per 4 javascript asp.net-routing razor asp.net-mvc-3 asp.net-web-api
这是我用来设置api url的代码:
var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client"})';
Run Code Online (Sandbox Code Playgroud)
在我的route.config中,路由如下所示:
routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/{controller}/{action}/{id}"
);
Run Code Online (Sandbox Code Playgroud)
我试图击中我的控制器上的动作是这样的:
[ActionName("clients")]
public IQueryable<Client> GetClients(int id)
{
return Uow.Clients.GetClients(id);
}
Run Code Online (Sandbox Code Playgroud)
我有一个javascript函数试图打这个api,但我得到一个404:
var getClients = function (id) {
return $.ajax(clientUrl + "/clients/" + id)
};
Run Code Online (Sandbox Code Playgroud)
当我调用getClients(1)时,url试图命中的是:
localhost:12345/clients/1
Run Code Online (Sandbox Code Playgroud)
而不是我期望的这个网址:
localhost:12345/api/client/clients/1
Run Code Online (Sandbox Code Playgroud)
知道这出错了吗?我让这个在另一个项目中工作,不记得我是否应该做其他事情.如果我检查javascript clientUrl =''.
Mar*_*nes 14
我遇到了这个答案如何创建ASP.NET Web API Url?哪有帮助.
我在GitHub上回答的示例代码
你可以改变你的@ Url.RouteUrl代码,包括两个动作名称和"ID"目前似乎不是可选的你的行动路线......这大概就是为什么它没有找到一个匹配,并返回一个空字符串.所以尝试:
var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client", action = "clients" id=@... })';
Run Code Online (Sandbox Code Playgroud)
NB. id=@... })';在最后...是什么id将成为模型等的var或属性...
您当然可以将ID设为可选,这也可以使用:
config.Routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
Run Code Online (Sandbox Code Playgroud)
您可能会发现它更干净以避免使用操作...客户端可以存在于自己的控制器中ClientsController,您可以使用路由和默认路由到它:
routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/client/clients/{id}",
defaults: new { controller="Clients" }
);
Run Code Online (Sandbox Code Playgroud)
那么这应该给你所需的响应:
var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Clients" })';
//api/client/clients/
Run Code Online (Sandbox Code Playgroud)
和...
var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Clients", id=@... })';
//api/client/clients/x
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6345 次 |
| 最近记录: |