I have 2 different Web APIs in Dot net 6. Each web API is a separate project in a Visual studio 2022 solution.
I need to setup middleware services in both API sin program.cs separately. I would like to create a separate class library and reuse the logic in both
These are the steps I took to implmenent AddCors
builder.Services.AddCors(o =>
o.AddPolicy("AllowOrigins", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader();
}));
public static class ServiceExt
{
public static void addCors(this IServiceCollection services) =>
services.AddCors(
// code to add CORS here...
);
}
}
But the issue is it's not recognizing AddCors extension method here..
using ServiceExtensions;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.addCors();
Just make sure that you have added the ServiceExtensions
project in project references of your API project.
My extension method.
using Microsoft.Extensions.DependencyInjection;
namespace ServiceExtensions
{
public static class ServiceExtensions
{
public static IServiceCollection ConfigureCORS(this IServiceCollection services)
=> services.AddCors(options =>
{
services.AddCors(o =>
o.AddPolicy("AllowOrigins", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader();
}));
});
}
}
Note : Install and Import the Microsoft.Extensions.DependencyInjection package to access the service collection in ServiceExtensions
project
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.