How to enable CORS in ASP.NET Core

For ASP.NET Core 6: var MyAllowSpecificOrigins = “_myAllowSpecificOrigins”; var builder = WebApplication.CreateBuilder(args); builder.Services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, builder => { builder.WithOrigins(“http://example.com”, “http://www.contoso.com”); }); }); // services.AddResponseCaching(); builder.Services.AddControllers(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseCors(MyAllowSpecificOrigins); app.UseAuthorization(); app.MapControllers(); app.Run(); See the See the official docs for more samples. For ASP.NET Core 3.1 and 5.0: You have … Read more

AddTransient, AddScoped and AddSingleton Services Differences

TL;DR Transient objects are always different; a new instance is provided to every controller and every service. Scoped objects are the same within a request, but different across different requests. Singleton objects are the same for every object and every request. For more clarification, this example from .NET documentation shows the difference: To demonstrate the … Read more

How to register multiple implementations of the same interface in Asp.Net Core?

I did a simple workaround using Func when I found myself in this situation. Firstly declare a shared delegate: public delegate IService ServiceResolver(string key); Then in your Startup.cs, setup the multiple concrete registrations and a manual mapping of those types: services.AddTransient<ServiceA>(); services.AddTransient<ServiceB>(); services.AddTransient<ServiceC>(); services.AddTransient<ServiceResolver>(serviceProvider => key => { switch (key) { case “A”: return serviceProvider.GetService<ServiceA>(); … Read more

How do you create a custom AuthorizeAttribute in ASP.NET Core?

The approach recommended by the ASP.Net Core team is to use the new policy design which is fully documented here. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a “policy” (e.g. [Authorize( Policy = “YouNeedToBe18ToDoThis”)] where the policy is registered in the application’s Startup.cs to execute some … Read more

Can’t use Count() in C#

Your resource is not a list but an object. Better implementation would be something like this. [HttpGet(“{id}”)] public IActionResult Get(string id) { using (var unitOfWork = new UnitOfWork(_db)) { var r = unitOfWork.Resources.Get(id); if (r == null) { return NotFound(); } return Ok(ConvertResourceModel(r)); } }