【问题标题】:Why isn't my angular controller hitting my Web Api Controller?为什么我的角度控制器没有击中我的 Web Api 控制器?
【发布时间】:2014-12-03 13:54:20
【问题描述】:

我正在尝试从服务器获取测试客户列表。我知道 Web API 控制器正在从数据库接收数据,因为我有围绕它的单元/集成测试;但是,当我尝试将数据拉到我的角度控制器时,我会收到 500 状态码。

角度控制器:

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

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService) {
    $scope.customers = { Key: "", Value: "" };
    customerService.getTest($scope);
});

surchargeIndex.service('customerService', [
    '$http', function($http) {
        this.getTest = function ($scope) {
            return $http({
                method: "GET",
                url: "api/Customer/GetTest",
            })
            .success(function (data) {
                $scope.customers = data;
            })
            .error(function () {
                $scope.error = "Failed to load customers!";
            });
        }
    }
]);

网页接口:

[RoutePrefix("api/Customer")]
public class CustomerController : ApiController
{
    private readonly ICustomerService _service;

    public CustomerController(ICustomerService service)
    {
        _service = service;
    }

    [Route("GetTest"), HttpGet]
    public IEnumerable<IJsonResult> GetTest()
    {
        return _service.GetTest();
    }
}

我错过了什么?

【问题讨论】:

  • 你能检查一下 500 错误的详细信息吗?
  • @jadarnel27 它指出,资源加载失败。
  • 能否在 C# 代码中设置断点并查看是否抛出异常?我知道您提到您已经围绕此代码进行了自动化测试,但最好只是验证某些内容没有出错。

标签: c# asp.net angularjs asp.net-web-api


【解决方案1】:

Web API 默认不允许远程连接。

这称为Cross-origin resource sharing (CORS)。

Web API 2.2 通过提供EnableCorsAttribute 可以轻松启用CORS。

基本用法

[EnableCors("*", "*", "*")]
public class ResourcesController : ApiController
{
    ...

属性定义

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = false)]
public EnableCorsAttribute(
    string origins,
    string headers,
    string methods
)

要启用CORS 全局使用

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("www.example.com", "*", "*");
        config.EnableCors(cors);
        // ...
    }
}

您还需要从nuget 安装 CORS 包

Install-Package Microsoft.AspNet.WebApi.Cors

【讨论】:

  • 那么我需要为每个 WebApi 控制器执行此操作吗?
  • 不,如果您愿意,可以将其注册为全局属性。我已经编辑了我的答案以包含一个这样的例子。
  • 我是否必须将实际的本地主机(最终是生产站点)放在第一个参数中,或者现在可以是随机的吗?
  • 为什么 CORS 会在这里应用?从 OP 共享的代码来看,它是客户端代码 (JavaScript) 向 Web API 控制器发出请求。我没有看到任何表明发生跨域请求的信息。
  • @jadarnel27:你是认真的吗? JS 代码在客户端运行,Web API 在服务器上,看图。
猜你喜欢
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多