Configuring asp.net MVC4 web api route url in javascript returns an empty string

Here is the code that I use to set api url:

var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client"})'; 

In my route.config, the route is as follows:

 routes.MapHttpRoute( name: "ApiControllerAction", routeTemplate: "api/{controller}/{action}/{id}" ); 

And the action on my controller that I am trying to remove is the following:

 [ActionName("clients")] public IQueryable<Client> GetClients(int id) { return Uow.Clients.GetClients(id); } 

I have a function in javascript that tries to hit this api, but I get 404:

 var getClients = function (id) { return $.ajax(clientUrl + "/clients/" + id) }; 

When I call getClients (1), the url tries to hit, this:

 localhost:12345/clients/1 

Instead of my expected URL:

 localhost:12345/api/client/clients/1 

Any idea where this is going wrong? I worked on another project and cannot remember if there is anything else that I should do. If I check javascript clientUrl = ``.

+4
source share
2 answers

I came across this answer How to create an ASP.NET Web API URL? .

Sample code for my answer here on GitHub

You can change your @ Url.RouteUrl code to include both the action name and the "identifier", which is not currently optional for your action route ... perhaps this is why it was not possible to find a match and return an empty string. So try:

 var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client", action = "clients" id=@... })'; 

NB. id=@... })'; at the end ... as always, the identifier will be var or property on the model, etc.

Or

You can, of course, just make an optional ID, which will also work:

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

Or

You can find it cleaner to not use the action ... clients could live in their own ClientsController , and you can use the routes and default settings to route it:

 routes.MapHttpRoute( name: "ApiControllerAction", routeTemplate: "api/client/clients/{id}", defaults: new { controller="Clients" } ); 

Then this should give you the required answer:

 var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Clients" })'; //api/client/clients/ 

and...

 var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Clients", id=@... })'; //api/client/clients/x 
+14
source

Try installing clientUrl as follows:

 var clientUrl = '@Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client", action = "clients"})'; 

And then in change getClients :

 var getClients = function (id) { return $.ajax(clientUrl + "/" + id) }; 
0
source

Source: https://habr.com/ru/post/1437928/


All Articles