Web Api 404 error The resource cannot be found

2019-07-16 17:01发布

I try to use Web Api for send/get data from server. WebApiConfig.cs :

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}"
        );

RouteConfig.cs:

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 }
                    );
    }

Globa.asax.cs:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalConfiguration.Configure(WebApiConfig.Register);

    }

Api controller (ServicesController.cs):

public class ServicesController : ApiController
{

    public List<TreeMenuItem> LoadMetadata()
    {
        List<TreeMenuItem> itemsMenu = new List<TreeMenuItem>();
        TreeMenuItem dataSource = new TreeMenuItem("1", "DataSources", null);
        itemsMenu.Add(dataSource);
        return itemsMenu;
    }
}

I'm trying to access api from angularJS controller like bellow:

angular.module("App", ["ngRoute", "ngResource"])
.controller('MainController', ["$scope", "$http", MainController]);

function MainController($scope, $http) {
var baseUrl = "Services/LoadMetadata";
var params = {};
$http.post(baseUrl, params)
    .then(function (data) {
        $scope.roleList = data.data;
});
}

I get error 404 on $http.post for "Services/LoadMetadata"! I tried some version using route - same error 404. Any help?

1条回答
老娘就宠你
2楼-- · 2019-07-16 17:34

change the registration sequence...

    GlobalConfiguration.Configure(WebApiConfig.Register);  
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

register web-api-config before route-config because i guess route-config is meddling with the web-api-config...

also please do consider the standard practice of having all your api calls prefixed with api.

  config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}"
    );
查看更多
登录 后发表回答