【问题标题】:CORS are not working with Angular 5CORS 不适用于 Angular 5
【发布时间】:2018-03-24 17:28:28
【问题描述】:

我在 Angular 5 中有 ASP.NET Core API 和应用程序。我在 Startup.cs 中添加了代码以启用 cors 并允许所有来源,但它仍然给我一个错误

请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。响应的 HTTP 状态代码为 500。

以下是我的网络 api 代码:

  public void ConfigureServices(IServiceCollection services)
    {
        WriteToFile("In configure service");
        try
        {
            // Enable Cors
            services.AddCors();
            services.AddMvc();
        }
        catch
        {
            WriteToFile("Not Connected in StartUP");
        }
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        try
        {
            app.UseCors(builder =>
               builder.AllowAnyOrigin()
               .AllowAnyHeader()
               .AllowAnyMethod());

            app.UseMvc();

            WriteToFile("After cors use In configure");

        }
        catch(Exception ex)
        {
            WriteToFile("Error in  configure"+ex.Message);
        }
    }

【问题讨论】:

  • 如果说不能注入服务,它会给你这个错误。尝试更清楚地看到错误正是关于 CORS
  • 对不起,我是 angular 和 web api 的新手,但是如何找到根本原因
  • 从您首先导航到的控制器中远程构造参数并检查它是否进入构造函数
  • 不它没有放弃那个控制器构造函数,但我仍然不确定为什么会这样。你能帮帮我吗
  • 服务器出错,与CORS无关。

标签: angular asp.net-core


【解决方案1】:

嘿,我觉得你应该放

[EnableCors(origins: "**http:/...(Here the website you want to enter)**", headers: "*", methods: "*")] 

就在控制器中的类之前。

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 2017-09-24
    • 2015-01-04
    • 2018-06-08
    • 1970-01-01
    • 2016-06-04
    • 2018-06-01
    • 1970-01-01
    • 2020-11-19
    相关资源
    最近更新 更多