Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting asp.net MVC4 web api route url in javascript is returning empty string

Here is the code that I am using to set the api url:

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

In my route.config the route looks like this:

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

And the action on my controller that I am trying to hit is this:

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

I have a function in javascript that is trying to hit this api, but I am getting a 404:

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

When I call getClients(1) the url is trying to hit is this:

localhost:12345/clients/1

Rather than my expected url of this:

localhost:12345/api/client/clients/1

Any idea where this is going wrong? I had this working in another project and can't remember if there is something else I am supposed to do. If I inspect the javascript the clientUrl = ''.

like image 369
ledgeJumper Avatar asked Dec 08 '22 20:12

ledgeJumper


1 Answers

I came across this answer How to create ASP.NET Web API Url? which helped.

Example code for my answer here on GitHub

You can alter your @Url.RouteUrl code to include both the action name and the "ID" which currently appears not to be optional for your action route... this is probably why it is failing to find a match and returning an empty string. So try:

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

NB. id=@... })'; at the end ... being what ever the id is going to be var or property on a model etc...

Or

You could of course just make ID optional which will also work:

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

Or

You may find it cleaner to avoid using an action... clients could live in its own controller ClientsController and you can use the routes and defaults to route to it:

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

Then this should give you the required response:

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
like image 192
Mark Jones Avatar answered Dec 22 '22 00:12

Mark Jones