King_Fisher King_Fisher - 27 days ago 5
Ajax Question

How to use the web api url across the mvc application

here is my piece of sample code

function AuthenticateLogin() {
$.getJSON('http://localhost:52293/api/APILogin/', function (data) {
if (data != null) {


The hosting url is below, which will be used across the mvc application, might be the controller/action will be varied across the application.


for example, here i have hard coded the above url in all places, If I'm moving the application to other machine,then it is not good to change the url again in each and every places. so, is there any way to handle this ?


Give your API action a static name:

public class APILoginApiController {
    [Route("", Name = "Login")]
    public ActionResult Login(string userName) {
        // ...

Then in your Razor JavaScript, you can utilize the UrlHelper by calling Url.HttpRouteUrl to dynamically build your URL for you.

$.getJSON('@Url.HttpRouteUrl("Login", new {})', function (data) {
    // ...

The advantage of this approach is that if you change anything about how the route is formulated, it's in the [Route] attribute on the action. Matching the name like that will use the routing engine to always create the correct path. Otherwise, you're still stuck with (partial) hard-coded paths throughout your JavaScript.

If your route requires any variables, then that is provided within the empty anonymous object as the second parameter for HttpRouteUrl().