【发布时间】: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() 注释是首选方式?或者是其他六个中的六个?
【问题讨论】: