Search code examples
javascriptasp.net-mvcasp.net-mvc-routing

Route to api work wrong


When i make GET request from http://localhost:5086/ it work great it send to api/FileBrowser, but when i try to make request from http://localhost:5086/Home/Index to api, to url added controller Home and request send to /Home/api/FileBrowser

Please help what i'm doing wrong?

ApiController with 2 methods

public FileBrowserModel Get()
    {
        var result = new FileBrowserModel();
        List<string> drives = new List<string>();
        foreach (var drive in DriveInfo.GetDrives())
        {
            var path = drive.Name;
            FileManagerCounter fmCounter = new FileManagerCounter(path);
            result.CountTo10Mb += fmCounter.CountTo10Mb;
            result.Countfrom10To50Mb += fmCounter.Countfrom10To50Mb;
            result.CountFrom100Mb += fmCounter.CountFrom100Mb;
            drives.Add(path);
        }
        result.SubDirectories = new List<string>(drives);
        return result;
    }
    [CacheOutput(ServerTimeSpan = 150)]
    [System.Web.Http.HttpGet]
    public FileBrowserModel Get(string path)
    {
        var result = new FileBrowserModel();

        try
        {
            try
            {
                result.ParentPath  = Directory.GetParent(path).FullName;
            }
            catch (Exception)
            {

            }

            var files = Directory.GetFiles(path).ToList();
            result.Files = new List<string>(files);
            result.CurrentPath = path;
            FileManagerCounter fmCounter = new FileManagerCounter(path);
            result.CountTo10Mb = fmCounter.CountTo10Mb;
            result.Countfrom10To50Mb = fmCounter.Countfrom10To50Mb;
            result.CountFrom100Mb = fmCounter.CountFrom100Mb;

            var subDirectories = Directory.GetDirectories(path).ToList();
            result.SubDirectories = new List<string>(subDirectories);
        }
        catch (Exception ex)
        {
            throw new HttpResponseException(HttpStatusCode.InternalServerError);
        }

        return result;
    }

js File

angular.module("FileBrowserApp", [])
.controller("fileBrowserController", function($scope, $http) {
    $scope.getFileBrowsing = function (path) {
        $scope.isLoading = true;
        if (path != null) {
            $http({
                url: "api/FileBrowser?path=" + encodeURIComponent(path),
                method: "GET"
            }).success(function (data) {
                $scope.fileBrowserModel = data;
                $scope.isLoading = false;
            });
        } else {
            $http({
                url: "api/FileBrowser",
                method: "GET"
            }).success(function (data) {
                $scope.fileBrowserModel = data;
                $scope.isLoading = false;
            });
        }
    };
    $scope.getFileBrowsing();
});    

Routes

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{path}",
            defaults: new { path = RouteParameter.Optional }
        );
    }
}
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Solution

  • If you're absolutely sure that your Web API layer will always exist one layer above the root domain then you can change your urls in your ajax calls to be:

    url: "/api/..."
    

    This calls the api relative to the root domain regardless of how the site may be structured.