asp.net mvc5 webapi2, how to get my webapi url via razor syntax?

asp.net-mvc, asp.net-web-api, knockout.js, razor

Solution

@Url.HttpRouteUrl("NameOfRoute", { controller = "Settings" })

or

@Url.RouteUrl("NameOfRoute", { httproute = "httproute", controller = "Settings" })

...as for the `routeName` parameter, I think usage of that might depend on whether or not you are using attribute routing or not. I believe the attribute routing that ships with MVC5 and WebAPI2 requires that your WebAPI attribute routes be named in order to be able to generate them with the `UrlHelper` (though it does not require that your MVC routes be named). If you are using traditional routing however, you may be able to omit the first parameter and not have to name the route at all.

One of the possible duplicates you were looking for may be here: How do I generate a webapi url from an MVC view?

Problem

I am sure this is a dupe, but I can't find the correct answer. It's simple enough. On a view in my application (that is within an Area if that matters) I need to get the url for a webapi controller in the root of my project (/api/settingscontroller). How do I get this url in the view (via razor) so I can pass it into a javascript knockout view model? Right now I have this: ``` ko.applyBindings(new UserSettingsViewModel('api/settings/', userId)); ``` with appends that url to the location I am at. I want this: ``` locahost:1234/api/settings/ ``` but I am getting this: ``` localhost:1234/settings/api/settings/ ``` the first 'settings' in the url is the area that I am in.

Original source

Related problems