Adam R. Grey Adam R. Grey - 2 months ago 5
ASP.NET (C#) Question

What's the right way to query my own API?

I have a web application that has regular webpages and an API. the regular controllers are in Controllers/, the API controllers are in Controllers/API.

On one of my views I can call

$.getJSON("/API/PRAXA/FO")


but that only works in development. In production, the application is in a subdirectory, so I would have to call

$.getJSON("/DMR/API/PRAXA/FO")


How can I determine this properly at run-time, so it works in both development and production?

I tried using

@Html.RouteLink("hiddenLink", "DefaultApi", new { action = "FO", controller = "PRAXA" }, new { id = "hiddenLink" })


but its
href
attribute is giving me null in both environments.

Answer

Use UrlHelper.HttpRouteUrl with the controller, actions and parameters. The helper will generate the full URL which will work in both development and production.

$.getJSON('@Url.HttpRouteUrl("DefaultApi", new { action = "FO", controller = "PRAXA" } )')

How do I generate a webapi url from an MVC view

Comments