【问题标题】:Issue configuring AngularJS SPA template with Web Api使用 Web Api 配置 AngularJS SPA 模板的问题
【发布时间】:2015-04-29 11:55:53
【问题描述】:

我正在尝试将 VS 2013 的 AngularJS SPA 模板与 Web Api 一起使用,但应用程序永远不会进入我的控制器,即使它进入调用该控制器的 app.js 部分,这是我的设置:

App_Start 文件夹内的WebApiConfig.cs

using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
//using System.Web.Mvc;

namespace App.TheForm
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Controllers 文件夹内的FormController.cs:

namespace App.TheForm.Controllers
{
    public class FormController : ApiController
    {
        public IEnumerable<Dictionary<string, object>> GetFormList()
        {
            List<DataRow> formList = new List<DataRow>();
            SqlConnection con = new System.Data.SqlClient.SqlConnection(@"Data Source=MyConnection;Initial Catalog=Forms;Integrated Security=True");

            con.Open();
            SqlCommand cmd = new SqlCommand("sp_Get_FormList", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter pFormId = new SqlParameter("@FormId", 3);

            cmd.Parameters.Add(pFormId);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            try
            {
                da.Fill(dt);
                itList<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                Dictionary<string, object> row;

                foreach (DataRow dr in dt.Rows)
                {
                    row = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        row.Add(col.ColumnName, dr[col]);
                    }
                    rows.Add(row);
                }
                return rows;
            }
            catch (Exception ex)
            {

            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }

            return null;
        }            
    }
}

AngularJS 控制器:

app.controller('FormController', function ($scope, $http) {
    $http.get('api/form/getformlist').success(function (data) {
        $scope.formlList = data;
    }).error(function () {
        alert('Error reading JSON file.');
    });

    }
});

index.cshtml

@{
    PageData["title"] = "AngularJS SPA Template for Visual Studio";
}
<h2>Welcome!</h2>
<p>This is just a demo page.</p>

<table ng-app="app" border="1" ng-controller="FormController">
    <tr ng-repeat="form in formlList" ng-class-odd="'odd'" ng-class-even="'even'">
        <td>
            {{form[0]}}
        </td>
        <td>
            {{form[1]}}
        </td>
    </tr>
</table>

App_Start 内的RouteConfig.cs:

namespace App.TheForm
{
    using System.Web.Routing;

    using App.TheForm.Routing;

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.Add("Default", new DefaultRoute());
        }
    }
}

感谢任何帮助。

更新:我只在使用 AngularJS SPA 模板时遇到这个问题。当我使用带有 Web Api 的 Empty Web Application 重新创建这个项目时,一切正常。我认为 AngularJS SPA 模板搞乱了项目的配置和路由。

【问题讨论】:

  • 你能把涉及的 HTML 贴出来吗?
  • 刚刚发布在我的问题底部
  • 您在 WebAPI 中的路由模板看起来很奇怪......api/{controller}/{id} 与您拥有的路由不匹配,api/{controller}/{action}
  • 我强烈推荐在 WebAPI2 中使用属性路由。 asp.net/web-api/overview/web-api-routing-and-actions/…
  • 确实将其更改为config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}", defaults: new { action = RouteParameter.Optional },但没有更改

标签: angularjs asp.net-web-api asp.net-web-api2 single-page-application asp.net-web-api-routing


【解决方案1】:

我会把它改成:

[RoutePrefix("api/form")]
public class FormController : ApiController
{
    [Route("getFormList")]
    public IEnumerable<Dictionary<string, object>> GetFormList()

然后我相信你的电话应该会成功。

【讨论】:

  • 不幸的是,正如我在顶部的更新部分中提到的那样,似乎是 AngularJS SPA 模板导致了问题。
  • 这是哪个模板?可以发个链接吗?
  • 在 Visual Studio Premium 2013 中选择在 Templates->Visual C#->Web 下创建新项目时,我得到了该模板。它被称为 AngularJS SPA 模板。
  • 我假设你有一个插件可以提供,因为我没有那个模板。
  • 也许我不久前从在线模板部分下载了它。
【解决方案2】:

在客户端使用$http.get('api/form') 而不是$http.get('api/form/getformlist')

【讨论】:

  • 智敏,感谢您的帮助。我已经尝试过了,但结果是一样的。尤其是当有多个 GET 方法时。我认为问题出在配置中,因为应用程序似乎不知道“api/form”的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 2014-10-08
  • 2015-07-03
  • 2017-05-01
  • 1970-01-01
  • 2016-12-10
  • 2017-05-14
相关资源
最近更新 更多