简体   繁体   中英

API Calls to controller is breaking after deploying to IIS

I am invoking API calls to get JSON data from server using javascript.

$(function () {

    var customersTable = $('#Customers');
    var returnCustomersTable = UpdateDataTable(customersTable, "/Customers/Loaddata");
}

This works fine when I am working with Visual studio Dev environment , because my web application is on root and so all javascripts Works fine.

Example:

My WebSite URL: http://localhost:4391
API Calls will be: http://localhost:4391/Customers/Loaddata

This works fine.

But when I deploy application to IIS, my website URL will be,

My WebSite URL: http://localhost/MyAppName

But API calls would still be,
API Calls will be: http://localhost/Customers/Loaddata , which results in not found.

Since I am using javascript in a separate file , I wont be able to do URL.Action .

The other option would be to create a base URL for dev and prod and the append with each servcie call.

But I am thinking if there is any other way.

The routing configuration in ASP.NET MVC is designed to serve as the single place in the application where all of the URLs can be maintained.

It helps considerably with maintenance of the project if all URLs are generated using routing through one of the UrlHelper based methods, such as Url.Action() rather than hard coded in controllers and views.

As long as your JavaScript is in an MVC view, you can just resolve Url.Action inline.

$(function () {

    var customersTable = $('#Customers');
    var returnCustomersTable = UpdateDataTable(customersTable, 
        '@Url.Action("Loaddata", "Customers")');
}

If the JavaScript is in a separate file outside of MVC, consider passing the URL through a variable or function parameter.

This routing feature also makes it easier to deploy ASP.NET MVC, because the generated URLs will adapt to use the application path when the application is not deployed to the root website virtual directory.

Application running in IIS web site root:

/Customers/Loaddata

Application running in virtual subdirectory configured as IIS Application named "MyAppName":

/MyAppName/Customers/Loaddata

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM