Jeffrey
Jeffrey

Reputation: 472

ASP.NET Core 6 - Cors dependency issue in another project

I have multiple ASP.NET Core 6 Web API projects. Each api is used by the same client app.

In each API, I had to manually setup CORS with exactly the same config.

I want to avoid code duplication by creating a small dedicated project called CorsSetup.

I created a class library project to provides methods for the CORS setup. But AddCors and UseCors are not found, I don't know what I should include in the project to make this work.

Here's a code example :

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;

namespace Company.CorsTool;

public static class ServiceExtension
{
    public static string allowSpecificOriginsName = "AllowCors";
    
    public static string[] allowedDomainProd = new string[] {  "http://example.com" };

    public static string[] allowedDomainDebug = new string[] { "https://prodexample.com" };
    
    public static void AddCompanyCors(this IServiceCollection services, bool isDev = false)
    {
        services.AddCors(
            options => options.AddPolicy(allowSpecificOriginsName,
                builder =>
                {
                    builder
                        .WithOrigins(isDev ? allowedDomainDebug.Concat(allowedDomainProd).ToArray() : allowedDomainProd)
                        .AllowCredentials()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                })
        );
    }

    public static void UseCompanyCors(this IApplicationBuilder app, bool isDev = false)
    {
        app.UseCors(allowSpecificOriginsName);
    }
}

Upvotes: 0

Views: 172

Answers (1)

Karl-Johan Sjögren
Karl-Johan Sjögren

Reputation: 17612

In your project file (Company.CorsTool.csproj maybe?) you need to add a framework reference for ASP.NET Core like this.

<ItemGroup>
  <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

Or you can change your whole project to a web project, though that also adds some other stuff such as analyzers and webdeploy support which probably isn't needed. To do that just change the <Project> element to include the Microsoft.NET.Sdk.Web SDK.

<Project Sdk="Microsoft.NET.Sdk.Web">

Upvotes: 1

Related Questions