Web Api 404错误无法找到资源

时间:2014-10-20 10:06:48

标签: angularjs asp.net-web-api angularjs-http

我尝试使用Web Api从服务器发送/获取数据。 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控制器(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;
    }
}

我正试图从angularJS控制器访问api,如下:

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

我在$ http.post上收到“Services / LoadMetadata”的错误404! 我尝试了一些使用route的版本 - 同样的错误404。 有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

更改注册顺序......

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

在route-config之前注册web-api-config,因为我猜route-config正在干扰web-api-config ......

也请考虑将所有api调用以api为前缀的标准做法。

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