C# 角应用中为什么需要CORS

C# 角应用中为什么需要CORS,c#,angularjs,asp.net-mvc-4,asp.net-web-api,C#,Angularjs,Asp.net Mvc 4,Asp.net Web Api,我有使用MVC、angular.js、实体框架和Webapi的应用程序。 我的Webapi在同一个解决方案中,但在不同的项目中,所以它有自己的端口。在我的angular服务中,我尝试调用webapi,就像 app.service('MyService', function coursesService($http) { var self = this; self.addData = function (data, config) { return $http.post('http://

我有使用MVC、angular.js、实体框架和Webapi的应用程序。 我的Webapi在同一个解决方案中,但在不同的项目中,所以它有自己的端口。在我的angular服务中,我尝试调用webapi,就像

app.service('MyService', function coursesService($http) {
var self = this;

self.addData = function (data, config) {
    return $http.post('http://localhost:1234/api/Test', JSON.stringify(data), config)
   .success(function (data, status, headers, config) {
       return data;
   })
   .error(function (data, status, header, config) {
       return data;
   });
}
});
但当应用程序运行时,它抛出了错误的跨源请求。因此,在我的webapi的webapiconfig.cs中,我必须在Register方法中编写以下代码

var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

然后我消除了这个错误。但我想知道的是,这是否是一个常见问题,以及避免它的最佳方法是什么?

可能重复的是它是怎样的。如果将web api控制器放入MVC项目中,如/controllers/api,则不必启用CORS来访问api。如果要隐藏api,另一种解决方案是发回控制器,然后使用Refit等工具创建对api的web请求。这样,如果您决定将api拆分到一个单独的web服务器上,您只需更改告知re fit在何处找到api端点的配置文件。