【问题标题】:AngularJS controller is not reaching webapiAngularJS 控制器没有到达 webapi
【发布时间】:2015-09-21 19:17:14
【问题描述】:

为了在使用 angularjs 之前进行爬行,我创建了一个简单的应用程序来使用 webapi 显示来自 sql server 表的结果。不幸的是,webapi 从未被调用,因为路由错误,但我不知道如何解决。 fiddler 显示 404 错误。

cshtml如下,定义了app和controller。

<script type="text/javascript">

var app = angular.module('streamApp', []);

app.controller('streamController', function($scope, $http){

    $scope.loading = true;
    $scope.addMode = false;

    //Used to display the data   
    $http.get('/api/Stream/').success(function (data) {
        $scope.streams = data;
        $scope.loading = false;
    })
    .error(function () {
        $scope.error = "An Error has occured while loading streams!";
        $scope.loading = false;
    });

});

</script>

cshtml文件中的渲染部分是

<div data-ng-app="streamApp" data-ng-controller="streamController" class="container">
....
</div>

webapi 类位于 MVC 项目中名为 WebApi 的文件夹中,但由于它永远无法访问,因此显示其代码毫无意义。无论如何,它是非描述性的。

路由配置如下:

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

    }
}

我不确定是否需要在 angularjs 代码或 mvc 路由配置中指定路由指令,以及要提供哪些功能或配置。我已经尝试将 webapi 类移动到 Controllers 文件夹,结果相同 - http 404。任何有关如何使此示例获取 webapi 代码的建议将不胜感激。


好热的数字......我通过将注释添加到我的 webapi 类方法解决了眼前的问题

    [Route("api/stream")]
    [System.Web.Http.HttpGet]
    public IEnumerable<Models.StreamViewModel> Get()
    {
       .....
    }

所以现在的问题是是否应该使用 RouteConfig 作为更好的做法?还是 Route() 注释是首选方式?或者是其他六个中的六个?

【问题讨论】:

    标签: angularjs asp.net-web-api


    【解决方案1】:

    回答您更新的问题,路由的最佳实践

    Route() 注释是执行此操作的首选方式。

    MVC 5 支持一种新的路由类型,称为属性路由。作为 顾名思义,属性路由使用属性来定义路由。 属性路由让您可以更好地控制 Web 中的 URI 应用。

    早期的路由风格,称为基于约定的路由,是 仍然完全支持。事实上,您可以在 同一个项目。

    属性路由还有其他优点,比如

    1. 它将路由信息与控制器动作相邻 实现该路线。这有助于调试和故障排除, 以及提供快速搜索路线的能力 解决方案中的信息。

    2. 它降低了更改路线过程中的风险。在 RouteConfig.cs 或 WebApiConfig.cs(在 Web API 解决方案的情况下), 可能会无意中改变错误的路线或 否则会对您的应用程序的其他部分产生不利影响。

    3. 您可能还希望包含可接受的 HTTP 方法、允许的用户类型和注册优先级,如果包含在 基于属性的路由,将所有这些信息放在一起 地点。

    这篇文章在上述方面为我提供了灵感和强化,并且更详细地介绍了: http://kevinmontrose.com/2011/07/25/why-i-love-attribute-based-routing/

    【讨论】:

      【解决方案2】:

      您可以使用其中任何一个,但如果没有注释,您的端点将是 api/get 而不是 api/stream(假设您没有重命名您的方法)。

      【讨论】:

        【解决方案3】:

        首先,您应该使用 ApiController 而不是 Controller,因为它扮演 api 操作的角色。

        其次,如果我们看一下,您似乎创建了一个名为 ApiController 的控制器和一个名为 Stream 的函数。否则,这是对使用 MVC 设计 Web 集成的误解。

        App_Start\WebApiConfig.cs:

        using System.Web.Http;
        
        class WebApiConfig
        {
            public static void Register(HttpConfiguration configuration)
            {
                configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}",
                    new { id = RouteParameter.Optional });
            }
        }
        

        Global.asax.cs:

        using System.Web.Http;
        
        ...
        
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
        
            RegisterGlobalFilters(GlobalFilters.Filters);
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        

        and ApiControllerNameController: //Controller字关闭文件名,不写就会到达:

        using System;
        ..
        ..
        ..
        
        namespace MvcApplication1.Controllers
        {
            public class ValuesController : ApiController
            {
                // GET api/values/MethodName
                public IEnumerable<int> MethodName()
                {
                    return new List<int> { 1, 2, 3 };
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-19
          • 1970-01-01
          • 2012-03-30
          • 2015-02-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多