.Net core 2 console appsettings transform - appsettings

I am trying to add appsettings transformation to a .net core 2 console application e.g.
appSettings.json
appSettings.Test.json
appSettings.Prod.json
I have found the following code works for asp.net core:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange:
true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional:
true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
However, I don't know how to get env.EnvironmentName because there is no IHostingEnvironment in a console app.
Any help will be appreciated

Couldn't find anything else so using preprocessor directives for now
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if
public Startup()
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange:
true)
#if RELEASE
.AddJsonFile($"appsettings.Release.json", optional:
true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

Related

How to enforce lowercase routes in .NET 6?

I would like to enforce lowercase routes in .NET 6 API project.
Here is my Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Here is my WeatherForecastController.cs:
using Microsoft.AspNetCore.Mvc;
namespace Weather.API.Controllers
{
[ApiController]
[Route("weatherforecast")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
I expect only the lowercase route (https://localhost:7243/weatherforecast) to work, but the route w/ pascal/uppercase works as well (https://localhost:7243/Weatherforecast)
I thought I can add builder.Services.AddRouting(options => options.LowercaseUrls = true); and app.UseRouting(), but I'm still able to access the route with pascal/uppercase: https://localhost:7243/Weatherforecast.
Here is the modified Program.cs file that I tried, but doesn't work:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRouting(options => options.LowercaseUrls = true);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseRouting();
app.MapControllers();
app.Run();
To generate lowercase URLs, add the following to Program.cs.
(Note: this does not enforce lowercase URLs).
// generate lowercase URLs
builder.Services.Configure<RouteOptions>(options =>
{
options.LowercaseUrls = true;
});
var app = builder.Build();
To enforce lowercase URLs, create an IRule-based rule that will redirect any uppercase URLs to lowercase URLs.
see this stackoverflow answer and IRule-based rule documentation.
Once you created an IRule-based rule (i.e., RedirectLowerCaseRule), add the following to Program.cs:
var app = builder.Build();
// enforce lowercase URLs
// by redirecting uppercase urls to lowercase urls
var options = new RewriteOptions().Add(new RedirectLowerCaseRule());
app.UseRewriter(options);

Attempts of migrate from net core 2.2 to 3.0

Good Morning
I'm migrating from 2.2 to 3.0 and then moving to 3.1 in net core with visual studio 2019
my first attempt was the most basic:
docs of Microsoft
Although it is a reduced version, I add it to my code leaving the packages that I still have to use for my project and it does not work ... result: 404
second try:
err_connection_refused
change the ip project of both http and https in addition to comparing it with the .json
result: 404 ERR_CONNECTION_REFUSED
third try:
migrate 2.2 to 3.0 stackoverlofw
reduce it as much as possible but without success too
the fourth attempt was the most "promising"
https://github.com/StackExchangeExamples/DotNetCoreTargetDotNetFramework/tree/master/BasicCoreWebsite
since it showed a "complete" example of how a project with version 3.0 should look
the result: a page that says "hello world" instead of a 404, is not something successful but better than a 404 is not it?
The idea of ​​this post is not only to solve my situation so that I do not get kicked out (lol) but to create as much as possible a complete functional example for future people with the same problem.
Thank you very much in advance and the data you require I will upload with pleasure!
UPDATE (i add the startup.cs)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using HistoriaClinica.IServicio;
using HistoriaClinica.IServicio.Servicio;
using System;
using System.IO.Compression;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Session;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace HistoriaClinica
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
services.AddDistributedMemoryCache();
services.AddSession();
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
services.AddMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
services.AddDataProtection().UseCryptographicAlgorithms(
new AuthenticatedEncryptorConfiguration()
{
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
});
// services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddResponseCompression(options =>
{
options.Providers.Add<GzipCompressionProvider>();
options.EnableForHttps = true;
options.MimeTypes = new[]
{
// General
"text/plain",
// Static files
"text/css",
"application/javascript",
// MVC
"text/html",
"text/xml",
"application/json",
"text/json",
"image/png",
"image/jpeg",
"image/svg+xml",
"application/octet-stream",
"application/font-woff",
"application/pdf"
};
});
services.Configure<GzipCompressionProviderOptions>(options =>
options.Level = CompressionLevel.Optimal
);
services.AddMemoryCache();
// Add application services.
services.AddSingleton<ILoggerServicio, LoggerServicio>();
services.AddScoped<IEncriptaServicio, EncriptaServicio>();
services.AddSingleton<IHttpServicio, HttpServicio>();
services.AddScoped<IPacienteServicio, PacienteServicio>();
services.AddScoped<IProfesionalServicio, ProfesionalServicio>();
services.AddScoped<IEspecialidadServicio, EspecialidadServicio>();
services.AddScoped<ILaboratorioServicio, LaboratorioServicio>();
services.AddScoped<IUsuarioServicio, UsuarioServicio>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ISessionServicio, SessionServicio>();
services.AddScoped<IImagenServicio, ImagenServicio>();
services.AddScoped<INoticiaServicio, NoticiaServicio>();
services.AddScoped<IResponseServicio, ResponseServicio>();
services.AddScoped<IClienteServicio, ClienteServicio>();
// services.AddMvc(options => options.EnableEndpointRouting = false);
services.AddControllers(options => options.EnableEndpointRouting = false);
services.AddControllersWithViews(options => options.EnableEndpointRouting = false);
services.AddRazorPages().AddMvcOptions(options => options.EnableEndpointRouting = false);
// Cron jobs
//services.AddCronJob<RecordatorioTurno24>(c =>
//{
// c.TimeZoneInfo = TimeZoneInfo.Local;
// c.CronExpression = #"*/1 * * * *";
//});
//services.AddCronJob<RecordatorioTurno48>(c =>
//{
// c.TimeZoneInfo = TimeZoneInfo.Local;
// c.CronExpression = #"* * * * *";
//});
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
app.UseSession();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Cuenta/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Default",
template: "{controller=Cuenta}/{action=Login}/{id?}");
});
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllerRoute(
// name: "default",
// pattern: "{controller=Cuenta}/{action=Login}");
//});
}
}
}

Is there a way to add a global directive for NS elements?

NativeScript provides a method to add custom properties to a component of your choice as mentioned here: https://docs.nativescript.org/core-concepts/properties.
Is there any way to add a custom property to all existing components? Just like Angular ng directives.
I'm using NS with plain JS.
EDITED: Added working code sample.
app.js
const application = require("tns-core-modules/application");
const Property = require("tns-core-modules/ui/core/properties").Property;
const View = require("tns-core-modules/ui/core/view").View;
const hiddenProperty = new Property(
{
name: "hidden",
defaultValue: false,
affectsLayout: true,
valueChanged: (target, oldValue, newValue) =>
{
console.log("New value is: " + newValue);
},
});
hiddenProperty.register(View);
application.run({ moduleName: "app-root" });
/*
Do not place any code after the application has been started as it will not
be executed on iOS.
*/

No service for type Identity.RoleManager - Identity.IdentityRole has been registered error

I use Microsoft Identity for the first time. I configured users and roles with IdentityUser and IdentityRole. I want to assign a role to users in Startup.cs. I wrote a method to make it which is
private async Task CreateUserRoles(IServiceProvider serviceProvider) {
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<int>>>();
var userManager = serviceProvider.GetRequiredService<UserManager<User>>();
var roleName = "Super Admin";
var roleCheck = await roleManager.RoleExistsAsync(roleName);
if (!roleCheck) {
Role role = new Role();
role.Name = roleName;
IdentityResult result = roleManager.CreateAsync(role).Result;
//IdentityResult roleResult = await roleManager.CreateAsync(new IdentityRole<int>(roleName));
}
User user = new User();
user.UserName = "someone";
user.Password = "someone";
user.Email = "someone#gmail.com";
ApplicationDbContext context = new ApplicationDbContext();
context.Users.Add(user);
context.SaveChanges();
user = await userManager.FindByEmailAsync("someone#gmail.com");
await userManager.AddToRoleAsync(user, roleName);
}
Hovewer there is a problem :
No service for type
'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]' has been registered.
How can I fix it?
Here is a Startup.cs
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Add MVC services to the services container.
services.AddMvc();
services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
services.AddSession(opt => { opt.Cookie.IsEssential = true; });
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(options => {
options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Settings");
options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql("User ID = postgres; Password = sa; Host = localhost; Port = 5432; Database = CCN; Pooling = true;"));
services.ConfigureApplicationCookie(options => {
options.LoginPath = $"/Account/Login"; //options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Account/Logout";
options.AccessDeniedPath = $"/Account/AccessDenied";
});
//Password settings
services.AddIdentity<User, Role>(o => {
o.Password.RequireDigit = false;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
//o.Password.RequiredLength = 3;
}).AddEntityFrameworkStores<ApplicationDbContext>().AddRoles<IdentityRole>()
.AddDefaultTokenProviders();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services) {
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
else {
app.UseExceptionHandler("/Home/Index");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
//Enable session
app.UseSession();
app.UseAuthentication();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});
//Create user role and assign it
CreateUserRoles(services).Wait();
}
}
No service for type
'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]' has been registered.
When registering IdentityRole for the AspNetCore Identity, the RoleManager<> type will be registered to the ServiceCollection as RoleManager<IdentityRole>.
Whenever you want to resolve the RoleManager<>, specify the identity role model registered in your startup as the type parameter. Which would be RoleManager<IdentityRole> in your specific case.
When calling GetRequiredService<RoleManager<IdentityRole>>() on the resulting service provider, GetRequiredService<RoleManager<IdentityRole>>() will throw the above exception.
Make the below modification:
In CreateUserRoles
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
Register the role services in the DI container (choose one of the two methods)
1.Use AddIdentity()
services.AddIdentity<User, IdentityRole()
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
2.Use AddDefaultIdentity , include roles by using the [AddRoles][1] method
services.AddDefaultIdentity<User>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
Reference : AddDefaultIdentity and AddIdentity
I tried those solutions but it didn't work. Then I recognize that I created an entity called Role which is derived from IdentityRole and its id data type is int. I changed
var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<int>>>();
this line with
var roleManager = serviceProvider.GetRequiredService<RoleManager<Role>>();
this one. Then it works.
On the other hand, thanks for your help!

MVC Core How to force / set global authorization for all actions?

How to force / set global authorization for all actions in MVC Core ?
I know how to register global filters - for example I have:
Setup.cs
services.AddMvc(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
and this works fine, but I can't add the same for Authorize:
options.Filters.Add(new AuthorizeAttribute());
I have error:
Cannot convert from 'Microsoft.AspNet.Authorization.AuthorizeAttribute()' to 'System.Type'
(Method .Add() needs IFilterMetadata type)
I know - from similar questions - that this works on MVC4-5... So something must changed on MVC Core...
Someone have any idea?
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
Add the following to your ConfigureServices in StartUp.cs. This is for token validation and force all calls to verify with token.
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})`
Add this to Configure method in StartUp.cs.
app.UseAuthentication();
Note: Use [AllowAnonymous] for those where you don't need it

Resources