4

I am trying to migrate my Web Api2 to ASP.NET core web api project. In my project we are using EnableCors features.

I found this document on Microsoft site, which I am using as a reference - https://docs.asp.net/en/latest/security/cors.html

As mentioned in 'Enabling CORS in MVC' section, I am trying to enable cors globally in ConfigureServices menthod like this -

services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });

However, I am getting this error which I couldn't understood-

The call is ambiguous between the following methods or properties: 'Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action)' and 'Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action)'

Refer Error Screenshot here - ERROR scrrenshot

Could anyone please let me know how do I enable CORS globally in my ASP.NET core WebApi project?

Project.json:

{
  "userSecretsId": "aspnet5-MVC6",
  "version": "1.4.0-*",
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "dependencies": {
    "Microsoft.ApplicationInsights.AspNetCore": "1.0.0",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Identity": "1.0.0",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.0",

    "Microsoft.AspNet.Cors": "6.0.0-rc1-final",

    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.EntityFrameworkCore": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.Extensions.Configuration.CommandLine": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.SecretManager.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dnxcore50"
      ],
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      }
    },
    "net461": {
      "dependencies": {
        "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": "1.0.0-preview2-final"
      }
    }
  },

  "publishOptions": {
    "exclude": [
      "**.user",
      "**.vspscc",
      "wwwroot",
      "node_modules"
    ]
  },

  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }
}
Sameer Pawar
  • 111
  • 2
  • 9
  • 1
    I suspect you mixed up dependencies. Post your project.json, likely one of your dependencies is fetching an outdated/different version of the options library – Tseng Aug 05 '16 at 16:50
  • @Tseng Added project.json – Sameer Pawar Aug 05 '16 at 17:09
  • Told ya, `"Microsoft.AspNet.Cors": "6.0.0-rc1-final" That's an outdated package. `"Microsoft.AspNetCore.Cors": "1.0.0"` is correct one – Tseng Aug 05 '16 at 17:14

2 Answers2

1

You mixed up the dependencies.

"Microsoft.AspNet.Cors": "6.0.0-rc1-final"

is an very old version and results in your solution having loaded two different assemblies with the same namespace and types and compiler doesn't know which one to use.

Change it to

"Microsoft.AspNetCore.Cors": "1.0.0"

All Microsoft.AspNet.* packages are very old and shouldn't be used. They all got renamed to Microsoft.AspNetCore.* with RC2

Tseng
  • 61,549
  • 15
  • 193
  • 205
  • I didn't realize...I was referring old documentation. Thank you :) – Sameer Pawar Aug 05 '16 at 17:20
  • any idea where I can refer correct documentation steps to enable cors globally in my ASP.NET core WebApi project? – Sameer Pawar Aug 05 '16 at 17:24
  • Api should be unchanged since rc1, but you can always look at the github examples or like in this case, use common sense or look at the samples used i.e. music store sample here: https://github.com/aspnet/MusicStore/tree/1.0.0/src/MusicStore. In fact you don't even need to add the dependency explicitly, because it's already referenced by the `Microsoft.AspNetCore.Mvc` package https://github.com/aspnet/Mvc/blob/1.0.0/src/Microsoft.AspNetCore.Mvc/project.json#L24 – Tseng Aug 05 '16 at 17:42
  • 1
    Hi @Tseng one more question reagrding CORS (please let me know if I need to raise new question) I have enable CORS globally in webapi. Add this block in startup - `services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("http://localhost:3000")); });` and marked controller with `[EnableCors("AllowSpecificOrigin")]` attribute. When I am sending GET request from Angular2 app, it works fine but POST doesn't. Am I missing anything here? – Sameer Pawar Aug 07 '16 at 11:00
  • POST request throws this error- `Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.` – Sameer Pawar Aug 07 '16 at 11:01
  • New question should be better with more details, there are multiple reasons, most likely an exception is thrown in your code and the exception middleware clears all headers set from other middlewares before the exception was raised or you could try to add `.AllowAnyMethod();` also see http://stackoverflow.com/a/37141865/455493 – Tseng Aug 07 '16 at 11:29
  • POST working after adding `AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();` Thanks again and I will raise new question going forward. – Sameer Pawar Aug 07 '16 at 12:55
0

Asp.Net Documentation Says:

To setup CORS for your application add the Microsoft.AspNetCore.Cors package to your project. Add the CORS services in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
      services.AddCors();
}

To enable CORS for your entire application add the CORS middleware to your request pipeline using the UseCors extension method. Note that the CORS middleware must precede any defined endpoints in your app that you want to support cross-origin requests (ex. before any call to UseMvc ).

You can specify a cross-origin policy when adding the CORS middleware using the CorsPolicyBuilder class. call UseCors with a lambda:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
     loggerFactory.AddConsole();
     if (env.IsDevelopment())
     {
        app.UseDeveloperExceptionPage();
     }
     // Shows UseCors with CorsPolicyBuilder.
     app.UseCors(builder =>
     builder.WithOrigins("http://example.com").AllowAnyMethod().AllowAnyHeader());
     app.Run(async (context) =>
     {
          await context.Response.WriteAsync("Hello World!");
     });
 }
Kalyan
  • 1,200
  • 1
  • 11
  • 23