Enable / Disable SSL on ASP.NET Core projects in Development - asp.net-core

On an ASP.NET Core project, I am using SSL in Production so I have in Startup:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc(x => {
x.Filters.Add(new RequireHttpsAttribute());
});
// Remaining code ...
}
public void Configure(IApplicationBuilder builder, IHostingEnvironment environment, ILoggerFactory logger, IApplicationLifetime lifetime) {
RewriteOptions rewriteOptions = new RewriteOptions();
rewriteOptions.AddRedirectToHttps();
builder.UseRewriter(rewriteOptions);
// Remaining code ...
}
It works fine in Production but not in Development. I would like to either:
Disable SSL in Development;
Make SSL work in Development because with current configuration it is not.
Do I need to set any PFX files on my local machine?
I am working on multiple projects so that might create problems?

You can configure a service using the IConfigureOptions<T> interface.
internal class ConfigureMvcOptions : IConfigureOptions<MvcOptions>
{
private readonly IHostingEnvironment _env;
public ConfigureMvcOptions(IHostingEnvironment env)
{
_env = env;
}
public void Configure(MvcOptions options)
{
if (_env.IsDevelopment())
{
options.SslPort = 44523;
}
else
{
options.Filters.Add(new RequireHttpsAttribute());
}
}
}
Then, add this class as a singleton:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
var builder = services.AddMvc();
services.AddSingleton<IConfigureOptions<MvcOptions>, ConfigureMvcOptions>();
}
Concerning the SSL point, you can easily use SSL using IIS Express (source)

If you don't want to use IIS Express then delete the https-address in Project Properties -> Debug section -> Under "Web Server Settings" -> Uncheck "Enable SSL".

just comment this line:
rewriteOptions.AddRedirectToHttps();
or in new versions of .Net core on Startup.cs comment:
app.UseHttpsRedirection();

Using #if !DEBUG, like below:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc(x => {
#if !DEBUG
x.Filters.Add(new RequireHttpsAttribute());
#endif
});
// Remaining code ...
}

Related

How to resolve Request to Long error in Asp.Net Core Azure B2C Configuraiton?

I am new to Asp.Net Core identity.
I have configured the startup as per below. When I run the code in a normal and incognito browser I get the below error.
I have cleared cookies as previous questions have suggested. What is interesting is a high number of cookies get created when loading the sign screen.
My issue is similar to those described in the below old articles. Both solutions seem outdated.
https://www.javaer101.com/en/article/18781756.html
https://blog.bitscry.com/2018/09/19/azure-ad-request-too-long/
using d365fl.DocumentGenerator.blazor_frontend.Data;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.IdentityModel.Logging;
namespace d365fl.DocumentGenerator.blazor_frontend
{
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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
ConfigureIdentiy(services);
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
}
private void ConfigureIdentiy(IServiceCollection services)
{
services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAdB2C");
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.Configure<OpenIdConnectOptions>(Configuration.GetSection("AzureAdB2C"));
}
// 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();
IdentityModelEventSource.ShowPII = true;
}
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.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
EDIT 1 - HTTP Request from Developer Toolbar
EDIT 2 - Screen Shot of Cookie data from Developer Toolbar / Network Tab
As we discussed in the comment, the issue is cause by too many cookies.
Please clear your cookies and modify your code to avoid endless loops and back and forth requests.
See this answer for more details.

Controller's action not invoked in ASPNETCORE console app running Kestrel

I'd like to have a console application running a standalone webserver accepting REST calls. My application is a .NET Core app with ASP .NET Core inside. I am completely new in this area. I found some examples and now I am struggling with controller route configuration. With the code below I always get "404 Not Found" error when using http://localhost:3354/api/Demo/Hello. Does anyone have an idea what am I doing wrong? Thank you for any suggestion!
I use VS2019 and ASPNETCORE 2.2.8.
class Program
{
static void Main(string[] args)
{
var builder = WebHost.CreateDefaultBuilder()
.ConfigureKestrel(options => options.ListenAnyIP(3354))
.UseStartup<Startup>();
builder.Build().Run();
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder builder, IHostingEnvironment env)
{
builder.UseMvc(delegate(IRouteBuilder routeBuilder)
{
routeBuilder.MapRoute("default", "api/{controller}/{action}");
});
}
}
Here comes the DemoController class.
public class DemoController : Controller
{
public IActionResult Hello()
{
return Ok("Hello world");
}
}
Your example is working fine for me on .net core 2.2
You could try explicitly declare routes like
[ApiController]
[Route("api/[controller]")]
public class DemoController : Controller
{
[HttpGet("hello")]
public IActionResult Hello()
{
return Ok("Hello world");
}
}
Also you could consider using Visual studio built-in templates of api web applications
After some investigation and comparison of my project with the sample project of Roman Kalinchuk I found out that the problem is that mvc controller provider doesn't look for controller types in my application assembly. It is enought to add my application assembly to the application parts collection.
See the .AddApplicationPart(typeof(DemoController).Assembly); line.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddApplicationPart(typeof(DemoController).Assembly);
}
public void Configure(IApplicationBuilder builder, IHostingEnvironment env)
{
env.EnvironmentName = "Development";
builder.UseMvc(delegate(IRouteBuilder routeBuilder)
{
routeBuilder.MapRoute("test", "api/{controller}/{action}");
});
}
}

How to get FeatureManager in ConfigureServices?

ASP.NET Core 3 Web Server.
appsettings.json
"FeatureManagement": {
"RouteStrategy": false
},
I'd like to get configuration and add route in the function.
How to get the FeatureManager here to analyze what features IsEnabled?
public void ConfigureServices(IServiceCollection services)
{
services.AddFeatureManagement();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
// <---------???
//

Setting Up ASP.NET Identity Core in an empty ASP.NET Core Web Application

I am trying to start a new web application project and I wanted to use the asp.net identity database (the one with all the AspNet tables (AspNetUsers, AspNetRoles etc)).
I have tried to follow numerous guides, these among other:
bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api-2-accounts-management/
johnatten.com/2014/04/20/asp-net-mvc-and-identity-2-0-understanding-the-basics/
tektutorialshub.com/asp-net-identity-tutorial-basics/%20%22ASP.Net%20Identity%20Tutoria
benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1
However when I tried to create the database I get this error.
I have also tried to do it by mimicking the template project (ASP.NET Core Web Application(.Net Core)) in Visual Studio with the same result or this one
This is how my project looks like, its basically the template minus the Controllers, Views and Models.
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// 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)
{
//var connectionString = #"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Northwind;Integrated Security=True;Pooling=False";
//services.AddEntityFramework()
// .AddSqlServer()
// .AddDbContext<NorthwindContext>(o =>
// o.UseSqlServer(connString));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
I just want to have an empty project with asp.net identity, preferably in SQL server instead of in localdb. Does anyone have a easy guide or know why it does not work for me?
EDIT1
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : this("Data Source=ACLAP;Initial Catalog=tmpCore;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False") { }
}
EDIT2
I have put up the project on github.
github.com/KiBlob/test
Just an idea, do you have defined the DefaultConnection in your appsettings.json file?
Mine looks like this:
{
"ConnectionStrings": {
"DefaultConnection": "Server=[SERVER];Database=[DB];Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
Try setting the connection there and then run Update-Database again.
Note: If you have multiple projects in your solution, make sure that the Default project in the package manager console is pointing to the project where the connection is set before running Update-Database.

Convention based approach for configuring services based on Operating System in Startup.cs

I recently created an ASP.NET service using 1.0.0-rc1-update1 on coreclr (x64). So, the service is capable of running on all supported Operating Systems; very cool! My service just exposes a simple "TODO" API and uses the Entity Framework 7.0 ORM. For persistence, it employs a Sqlite DB on Linux and SQL Server DB on Windows.
I am wondering if there is a convention based approach to allow Startup.cs to handle differing service configurations for the various Operating Systems? For example, my EF configuration differs because it uses Sqlite on Linux and SQL Server on Windows.
The following article does detail some convention based approaches to configuration, but it seems to only allow for different methods for the higher level abstractions of "Development", "Staging", "Production" environments:
https://docs.asp.net/en/latest/fundamentals/environments.html
Currently, I am just injecting the IRuntimeEnviroment in the constructor of Startup.cs and saving it. Then, when ConfigureServices is invoked, I check the OperatingSystem property of the IRuntimeEnvironment and adjust the EF configuration accordingly (my full Startup.cs provided below)...
Any guidance on other (or recommended) approaches would be greatly appreciated.
public class Startup
{
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
public IConfigurationRoot Configuration { get; set; }
public IRuntimeEnvironment RuntimeEnv { get; set; }
public Startup(IHostingEnvironment env, IRuntimeEnvironment runtimeEnv)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
RuntimeEnv = runtimeEnv;
}
public void ConfigureServices(IServiceCollection services)
{
if (RuntimeEnv.OperatingSystem == "Windows")
{
var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<TodoContext>(options => options.UseSqlServer(connectionString));
}
else if (RuntimeEnv.OperatingSystem == "Linux")
{
var connectionString = Configuration["Data:DefaultConnection:SqlLiteConnection"];
var path = PlatformServices.Default.Application.ApplicationBasePath;
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<TodoContext>(options => options.UseSqlite("Filename=" + Path.Combine(path, "TodoApp.db")));
}
services
.AddMvcCore(options =>
{
options.OutputFormatters.Clear();
options.OutputFormatters.Add(new HttpNotAcceptableOutputFormatter());
options.OutputFormatters.Add(new HttpNoContentOutputFormatter());
})
.AddJsonFormatters();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseIISPlatformHandler();
app.UseMvc();
loggerFactory.AddConsole(minLevel: LogLevel.Verbose);
loggerFactory.MinimumLevel = LogLevel.Debug;
}
}