Getting correct (relative) URLs to your ASP.NET Web API controller actions using JavaScript
Posted: (EET/GMT+2)
When you call ASP.NET Web API endpoints from JavaScript, it is tempting to hardcode URLs like /api/customers. This works fine until you change your routing, move the application under another virtual directory, or version the API.
A simple way to keep URLs correct is to let ASP.NET generate them server-side and pass them into your script.
In an MVC view or Razor layout, you can use Url.HttpRouteUrl or Url.Action:
<script type="text/javascript">
var customerApiUrl = '@Url.HttpRouteUrl(
"DefaultApi",
new { controller = "Customers" })';
// now you can use "customerApiUrl" in your fetch ("AJAX") calls
function loadCustomers() {
fetch(customerApiUrl)
.then(function (r) { return r.json(); })
.then(function (data) { console.log(data); });
}
</script>
If you prefer, you can store base URLs or route templates in data attributes:
<div id="api-root"
data-customer-url="@Url.HttpRouteUrl("DefaultApi", new { controller = "Customers" })"></div>
<script>
var root = document.getElementById("api-root");
var customerApiUrl = root.getAttribute("data-customer-url");
</script>
This way, if you change routing or deploy the application under a different virtual directory, your JavaScript still uses the correct relative URLs. The server remains the single source of truth for route generation, and the client just reads the values.