[英]Why isn't my angular controller hitting my Web Api Controller?
我試圖從服務器獲取測試客戶列表。 我知道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!";
});
}
}
]);
Web Api:
[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();
}
}
我錯過了什么?
默認情況下, 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.