VS2017 Web应用CORS:Access-Control-Allow-Origin

Posted

技术标签:

【中文标题】VS2017 Web应用CORS:Access-Control-Allow-Origin【英文标题】:VS2017 Web application CORS: Access-Control-Allow-Origin 【发布时间】:2018-12-11 04:46:06 【问题描述】:

我将Angular 6+ 用于将CRUD 呈现给SQL Database 的小型网站。我知道Angularclient-side framework,所以我使用Visual Studio 2017 创建了一个Web 服务,我使用的项目是web application ASP.NET Core,因为我在localhost 中测试它,Angular 运行在@987654332 @我的服务目前在port 53819

因此,我已经(或最后尝试)通过在我的 webservice 上安装 CORS NUGget 包并在控制器级别启用它来启用 Cross-Origin Resource Sharing (CORS),如图所示:

...    
namespace CIE_webservice.Controllers
    
        [Produces("application/json")]
        [Route("api/CIE")]
        [EnableCors(origins: "http://localhost:4200/", headers: "*", methods: "*")]
        public class CIEController : Controller
        
            [HttpGet]
            public IEnumerable<string> Get()
            
                return new string[]  "value1", "value2" ;
            
...

在我的Angular App 上,我使用了一个简单的ajax 请求,如下所示:

$.ajax(
      url: 'http://localhost:53819/api/CIE/',
      success: function()   console.log(" OK "); ,
      error: function()   console.log(" Error "); 
  );

就我可以获得的教程而言,我的代码还可以,但仍然出现错误:

Failed to load http://localhost:53819/api/CIE/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

即使 Ajax 请求有响应 200 OK,预览也会显示响应 json:

也许我错过了什么或者我没有很好地理解这个概念......如果需要更多信息来解决我的问题,请随时询问。

提前致谢。

【问题讨论】:

将 CORS 源硬编码到与客户端使用的端口不同的端口是否正常? @olleo 我不认为这是正常的,但因为是本地主机和初始配置,所以我就这样使用了。 【参考方案1】:

我在一个爱好项目中有类似的工作,所以我可以向你展示我做了什么来让它工作......

我在我的 Startup.cs 中这样做了

app.UseCors(options =&gt; options.WithOrigins(Configuration["trustedCors"].Split(' ')).AllowAnyMethod().AllowAnyHeader());

在我的配置文件中...

“trustedCors”:“http://localhost:60000https://localhost:60000http://glendesktop:60000https://glendesktop:60000”

我还记得在我的测​​试中,这个案例对 CORS 很重要。

【讨论】:

我已经尝试在app.UseMvc(); 之后和上面写下这一行,但得到错误:System.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.Extensions.Configuration.IConfiguration.this[string].get devolvió null.【参考方案2】:

根据 Glen 的回答和这个“tutorial”,我已经设法让事情正常进行。

在我的Startup.cs 文件中

...
public void ConfigureServices(IServiceCollection services) 
  services.AddCors();       /* <----- Added this line before de MVC */
  services.AddMvc();

...
public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
  if (env.IsDevelopment()) 
    app.UseDeveloperExceptionPage();
  
  app.UseCors(builder => builder.WithOrigins("http://localhost:4200")); /* <----- Added this line before de MVC */
  app.UseMvc();

在我的控制器文件CIEController.cs

...    
namespace CIE_webservice.Controllers 
  [Produces("application/json")]
  [Route("api/CIE")]
  [EnableCors(origins: "http://localhost:4200/", headers: "*", methods: "*")] /* <--- This line remains here or can be added at the action level*/
  public class CIEController : Controller 
    [HttpGet]
    public IEnumerable<string> Get() 
      return new string[]  "value1", "value2" ;
    
...

【讨论】:

以上是关于VS2017 Web应用CORS:Access-Control-Allow-Origin的主要内容,如果未能解决你的问题,请参考以下文章

vs2017web包有多大

使用 Spring Boot 和 Zuul 进行 CORS 预检请求的 Host vs Origin 标头

学习NetCore应用框架——01-使用vs2017创建Net Core MVC的Web 应用

Angular、CORS 和 Spring 的问题

ajax跨域(跨源)方案之CORS

vs2017运行不起来.net web程序,包不兼容