How does it Access appsettings from this c# Class Library Project? - c#

I saw the sample ASP.NET core Web Api at following website:
https://codewithmukesh.com/blog/dapper-in-aspnet-core/
It uses the dapper for accessing SQL database with 3 class library projects. In the c# class library project named "Dapper.Infrasstructure", the ProductRepository.cs program obtains the SQL connection string from appsettings.cshtml with code shown in CODE SEGMENT 1. It also uses IServiceCollection for registering services in setup.cs (see CODE SEGMENT 2). The library project includes three packages (See CODE SEGMENT 3).
Since there is no appsettings file in any class library. how does it access the settings that is in the main project "Dapper.WebApi"? The program was build with ASP.NET core 3.1. I compiled it using .NET 5. It wors just fine. I also checked the content of its setup.cs file (see CODE SEGMENT 4) and program.cs file (see CODE SEGMENT 5).
I tried to use the similar implementation method in an ASP.NET core MVC program. It could not get the SQL connection string from appsettings contained in the main web app from the C# class library project. What makes the accessing appsettings possible in Web API but not from MVC web app?
CODE SEGMENT 1
public class ProductRepository : IProductRepository
{
private readonly IConfiguration configuration;
public ProductRepository(IConfiguration configuration)
{
this.configuration = configuration;
}
public async Task<int> AddAsync(Product entity)
{
entity.AddedOn = DateTime.Now;
var sql = "Insert into Products (Name,Description,Barcode,Rate,AddedOn) VALUES (#Name,#Description,#Barcode,#Rate,#AddedOn)";
using (var connection = new SqlConnection(configuration.GetConnectionString("DefaultConnection")))
{
connection.Open();
var result = await connection.ExecuteAsync(sql, entity);
return result;
}
}
......
}
CODE SEGMENT 2
using Dapper.Application.Interfaces;
using Dapper.Infrastructure.Repository;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace Dapper.Infrastructure
{
public static class ServiceRegistration
{
public static void AddInfrastructure(this IServiceCollection services)
{
services.AddTransient<IProductRepository, ProductRepository>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
}
}
}
CODE SEGMENT 3
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.1.6" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.1" />
</ItemGroup>
CODE SEGMENT 4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
namespace Dapper.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddInfrastructure();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.IncludeXmlComments(string.Format(#"{0}\Dapper.WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory));
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Dapper - WebApi",
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
#region Swagger
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CleanArchitecture.WebApi");
});
#endregion
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
CODE SEGMENT 5
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Dapper.WebApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}

Related

Application doesn't load azure app config feature flag value but loads config values

I have a Blazor app that I want to use Azure app config.
I've successfully setup getting config values, however it doesn't find my feature flag.
When I inject an IConfiguration and query the value of a config value, like so Configuration["value"] the proper data is retrieved.
But when I try and check if my only feature flag is enabled (and it is) the result is always false, which I imagine is because the app can't find the feature flag, not because it's reading the value wrong (passing the name of a non-existant feature flag causes the method to return "false").
Startup.cs:
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Microsoft.FeatureManagement;
namespace OreNoAppu
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
services.AddControllersWithViews().AddMicrosoftIdentityUI();
// By default, all incoming requests will be authorized according to the default policy
services.AddAuthorization(options => options.FallbackPolicy = options.DefaultPolicy);
services.AddRazorPages();
services.AddServerSideBlazor().AddMicrosoftIdentityConsentHandler();
services.AddFeatureManagement();
services.AddAzureAppConfiguration();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days.You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAzureAppConfiguration();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
Program.cs:
using Azure.Core;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using BoomiLogReader.Utility;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
namespace OreNoAppu
{
public class Program
{
public static void Main(string[] args)
{
InitKeyVault();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration(config =>
{
var connection = KeyVaultReader.GetSecretValue("AzureAppConfigConnStr");
config.AddAzureAppConfiguration(options =>
options.Connect(connection).UseFeatureFlags());
}).UseStartup<Startup>());
// Initialises KeyVaultReader, which is used to retrieve secrets from Azure Key Vault.
public static void InitKeyVault()
{
// N'importe quoi, access to KeyVault and getting of the conn string works fine.
}
}
}
Code that should be getting the flag:
#using Microsoft.FeatureManagement
#inject IFeatureManager featureManager
#if (featureEnabled)
{
<h1>Yes</h1>
}
#code
{
bool featureEnabled = true;
protected override async Task OnInitializedAsync()
{
featureEnabled = featureManager.IsEnabledAsync("OreNoFlaggu").Result;
}
}
Debugging, I see that the method call "IsEnabledAsync" returns "false", but there is a "OreNoFlaggu" feature flag in my app config, that the application successfully connects and retrieves config values from, and said flag is enabled.
Any idea why it isn't working?
#Tessaract, does your feature flag happen to have a label in your App Config store. If so, please don't forget to pass the label when calling UseFeatureFlags() via FeatureFlagOptions.Label.

How does a C# Api read the appsettings.json?

I wonder how the startup.cs knows of the appsettings.json file, I can't seem to find a setting in the startup.cs or program.cs of the api.
Standard program.cs:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Standard startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
I tried to add appsettings.json to a console app but then I had to do the injection of the file manually. With this piece of code:
configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
.AddJsonFile("appsettings.json", false)
.Build();
The application knows about these appsettings files thanks to the call to the Host.CreateDefaultBuilder method in program.cs .
As mentioned here in the ASP.NET Core documentation, this method enables some default behavior, such as loading app configuration from:
appsettings.json.
appsettings.{Environment}.json.
User secrets when the app runs in the Development environment.
Environment variables.
Command-line arguments.

After migrating my app to ASP.NET Core 3.0, the previously valid Index URL returns 404

An app started in ASP.NET Core 2.0 (I think), then migrated to 2.1, then to 2.2, now I'm trying and failing to migrate it to 3.0...
I read and tried to apply instructions in the official migration docs, according to which I was supposed to (among others) replace services.AddMvc() with services.AddRazorPages() and app.UseMvc() with app.UseEndpoints(endpoints => {endpoints.MapRazorPages();}) if I was using Razor Pages. Since as far as I'm aware I was always using Razor Pages and never full-blown MVC, this is what I did.
Now previously working URLs return HTTP 404 instead of any content...
For instance, the / or /Index route does this, even though in the project directory there is a Pages/Index.cshtml file as well as a Pages/Index.cshtml.cs file. (Although oddly: maybe it is only the Index url that is failing - I just tried pointing my browser to /Error and it worked!)
Pages/Index.cshtml.cs content (unchanged from the working version):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Mon.Battle;
namespace mon.Pages
{
public class IndexModel : PageModel
{
public IndexModel(IBattleManager battleManager)
{
// I hope I don't have to lock this dict here, I'm only reading
configurationSerialized = battleManager.configurationSerialized;
}
public ConfigurationSerializedFormat configurationSerialized;
public void OnGet()
{
}
}
}
Pages/Index.cshtml also contains some content, but it is too long and too messy to post it here as a whole... But it should definitely return something and it was returning something before migrating to 3.0.
Page directives from the top of Index.cshtml are short enough however:
#* TODO: The site becomes ugly :( Should I start using Bootstrap, instead of trying to handcraft CSS? *#
#* Hey... I actually start to like how the site looks :) *#
#page
#using System.Text.Encodings.Web
#using Microsoft.Extensions.Configuration
#inject JavaScriptEncoder jsencoder
#inject IConfiguration conf
#using static System.Text.Json.JsonSerializer
#model IndexModel
#{
Layout = null;
}
These, unfortunately, had to change a bit from the pre-migration version: namely since 3.0 removed Newtonsoft.JSON, I had to replace it with System.Text.Json.
My current Startup.cs (I thought I applied instructions from the aforementioned docs precisely):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using mon.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mon.Chat;
using Mon.MatchMaker;
using Mon.Battle;
using Mon.Player;
namespace mon
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<IdentityOptions>(options =>
{
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.AddSignalR();
services.AddSingleton<IBattleManager, BattleManager>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
endpoints.MapHub<MatchMakerHub>("/mmrhub");
endpoints.MapHub<BattleHub>("/battlehub");
endpoints.MapRazorPages();
});
}
}
}
Previous Startup.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using mon.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Mon.Chat;
using Mon.MatchMaker;
using Mon.Battle;
using Newtonsoft.Json.Serialization;
using Mon.Player;
namespace mon
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.Configure<IdentityOptions>(options =>
{
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>().AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services
.AddSignalR()
.AddJsonProtocol(options =>
{
options.PayloadSerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddSingleton<IBattleManager, BattleManager>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chathub");
routes.MapHub<MatchMakerHub>("/mmrhub");
routes.MapHub<BattleHub>("/battlehub");
});
app.UseMvc();
}
}
}
What am I doing wrong? What did I miss? Why does /Index return HTTP 404?
If you ask for any more info I'll provide.
Once I had the issue with my .csproj file. Make sure your file(s) are not listed like:
<ItemGroup>
<Content Remove="Views\Extractor\Insert.cshtml" />
<Content Remove="Views\_ViewImports.cshtml" />
</ItemGroup>
This might happen when we copy paste the file/ change the build action etc.

Add an implementation of 'IDesignTimeDbContextFactory' to the project?

Currently following a course from early 2018.
After running Add-Migration Initial in the Package Manager Console
This is my error message ;
Unable to create an object of type 'AppDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
The link says to add...
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace MyProject
{
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
}
}
}
to my startup.cs...
This is my startup class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using BethanysPieShop.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using WebApplication5.Models;
namespace BethanysPieShop
{
public class Startup
{
private IConfigurationRoot _configurationRoot;
public Startup(IHostingEnvironment hostingEnvironment)
{
_configurationRoot = new ConfigurationBuilder()
.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(_configurationRoot.GetConnectionString("DefaultConnection")));
services.AddTransient<ICategoryRepository, CategoryRepository>();
services.AddTransient<IPieRepository, PieRepository>();
services.AddMvc();
}
// 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)
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
I'm using Entity Framework Core Tools 2.1.2
AppDbContext.cs
using BethanysPieShop.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<Pie> Pies { get; set; }
public class DbSet
{
}
}
}
Where/location do I implement their code in my code?
What variables do I change?
Last I remember this issue was caused because you're not using the proper WebHostBuilder Method name see this github issue
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
//.Net-core relies on Duck Typing during migrations and scaffolding
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Try putting this:
services.AddScoped(typeof(IDesignTimeDbContextFactory<BloggingContext>), typeof(BloggingContextFactory));
In Startup.cs, method ConfigureServices, below the services.AddTransient < IPieRepository, PieRepository >();
I hope you find it useful

How can I protect an asp.net core middleware with cookies?

I would develop an ASP.NET Core web API that redirects received HTTP API after cookie authentication.
Below my Startup.cs file:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MyProject.Middlewares;
namespace MyProject.Backend
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddTransient(typeof(ReverseProxyMiddleware));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCookiePolicy();
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseReverseProxyMiddleware();
}
}
}
And below my middleware:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
namespace MyProject.Middlewares
{
public class ReverseProxyMiddleware : IMiddleware
{
[Authorize]
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
// HTTP redirection...
}
}
}
Actually, if I try to perform an HTTP request without cookie I obtain 200 results. How can I protect my middleware?
Thanks

Categories