Hyphens in route, works with link, doesn't work directly - asp.net

I am trying to use hyphens in an URL route. In ASP.NET Core MVC. I setup a default MVC template.
The only thing I change is to add this first line:
[Route("hello-dude")]
public IActionResult Privacy()
{
return View();
}
Now, when I got to test the project, I click privacy and it shows the correct page and URL. (http://localhost:44386/hello-dude)
But when I go to the address bar and put that in manually, click enter, I get "site cannot be reached".
What is going on here?
Startup.Cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication8
{
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.AddControllersWithViews();
}
// 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("/Home/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.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}

Related

How to read the Azure App Configuration in Service Fabric ASP.NET Core Stateless Web API?

I need help to read the App Configuration in Service Fabric ASP.NET Core Stateless Web API. In the Normal ASP.NET Core Web API, we can use the Host CreateDefaultBuilder to read the config and use it in the Startup and other classes. If I try to inject in the Service Fabric Web API, it does not work. The Program.cs contains only the following.
private static void Main(string[] args)
{
try
{
// The ServiceManifest.XML file defines one or more service type names.
// Registering a service maps a service type name to a .NET type.
// When Service Fabric creates an instance of this service type,
// an instance of the class is created in this host process.
ServiceRuntime.RegisterServiceAsync("EmailAPIType",
context => new EmailAPI(context)).GetAwaiter().GetResult();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(EmailAPI).Name);
// Prevents this host process from terminating so services keeps running.
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
And the startup.cs contains
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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmailAPI
{
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 inject Host CreateDefaultBuilder in program.cs
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
{
options.Connect(ConnectionString)
.Select(ConfigValues).TrimKeyPrefix(qualtricsAppConfigPrefix + ":")
.UseFeatureFlags();
});
})
.UseStartup<Startup>());
I am running out of Ideas how to do. In Azure Function App we can do it in Startup, not sure how we can handle in Service Fabric ASP.NET Core Web API. Any examples please.
I have uploaded the sample project created in One Drive. Here is the link to it.
https://1drv.ms/u/s!Au2rKbF-hqWY61pykRlWRTI4DB8t?e=vz0c8z
Finally figured it out. For anyone who is interested here is it. If you have any better way to do it please let me know
public class Startup
{
private static string prefix = "";
public Startup(IConfiguration configuration)
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", false, false)
.AddEnvironmentVariables();
var builder = configurationBuilder.Build();
configurationBuilder.AddAzureAppConfiguration(o => AddApplicationKeysAppConfiguration(o, builder));
builder = configurationBuilder.Build();
configuration = builder;
Configuration = configuration;
}
private static void AddApplicationKeysAppConfiguration(AzureAppConfigurationOptions options, IConfigurationRoot configuration)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
environment = string.IsNullOrWhiteSpace(environment) ? Environment.GetEnvironmentVariable("Environment") : environment;
string connectionString = "";
options.Connect(connectionString)
.Select($"{prefix}*", environment).TrimKeyPrefix(prefix + ":")
.UseFeatureFlags(flagOptions =>
{
flagOptions.Label = environment;
});
}
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();
});
}
}
}

The name 'CertificateAuthenticationDefaults' does not exist in the current context

I'm trying to configure mTLS authentication with ASP.NET core 3.1 by using the example from Microsoft Docs but getting the error below
Error CS0103 The name 'CertificateAuthenticationDefaults' does not exist in the current context
The code I'm using for Startup.cs is below:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Data;
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddControllersWithViews();
// Configure the application to use the protocol and client ip address forwared by the frontend load balancer
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
// Configure the application to client certificate forwarded the frontend load balancer
services.AddCertificateForwarding(options => { options.CertificateHeader = "X-ARR-ClientCert"; });
// Add certificate authentication so when authorization is performed the user will be created from the certificate
services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme).AddCertificate();
}
// 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("/Home/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.UseForwardedHeaders();
app.UseCertificateForwarding();
app.UseHttpsRedirection();
app.UseRouting();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
Any suggestinos on fix will be appreciated
In order to overcome the error I have to add the following statement in the code :
using Microsoft.AspNetCore.Authentication.Certificate;
and install Microsoft.AspNetCore.Authentication.Certificate 3.1.20 package.

Why is the presence of middleware preventing execution of an endpoint?

I am a beginner at ASP.Net. Here is my startup.cs file:
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.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using CAPSWebServer.CapsDataModels;
namespace CAPSWebServer
{
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration config)
{
Configuration = config;
}
// 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.AddDbContext<CapsDataContext>(opts =>
{
opts.UseNpgsql(Configuration["ConnectionStrings:CAPSConnection"]);
opts.EnableSensitiveDataLogging(true);
});
}
// 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.UseStaticFiles();
app.UseRouting();
app.UseMiddleware<TestMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
And here is my TestMiddleware class:
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Threading.Tasks;
using CAPSWebServer.CapsDataModels;
namespace CAPSWebServer
{
public class TestMiddleware
{
private RequestDelegate nextDelegate;
public TestMiddleware(RequestDelegate next)
{
nextDelegate = next;
}
public async Task Invoke(HttpContext context, CapsDataContext dataContext)
{
if (context.Request.Path == "/test")
{
await context.Response.WriteAsync($"There are {dataContext.Charges.Count()} charges.\n");
await context.Response.WriteAsync($"There are {dataContext.Inventories.Count()} coils.\n");
}
}
}
}
This application is configured to listen on port 500 of my computer. When I run localhost:5000/test, I get the expected report of how many charges and coils I have in my database. But when I run localhost:5000 by itself, I get nothing. I think I should be getting "Hello, world". If I comment out out the call to UseMiddleware(), I get "Hello, world". Why does the middleware block the endpoint?
I am using Visual Studio 2019.
You need to call the
nextDelegate();
So that the next middleware down the line is executed.
The reason it works when the URL contains "/test" is because you are writing directly into the response stream.

Ocelot Caching : AddCacheManager Try specifying the type arguments explicitly error

New to Ocelot and .net core. I am trying to implement caching in .net core 3.0 microservice in Ocelot gateway. As per Ocelot guideline (https://ocelot.readthedocs.io/en/latest/features/caching.html)
As per second step, my startup.cs looks like:
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace MS_APIGateway
{
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.AddOcelot().AddCacheManager(x => **// Getting error here**
{
x.WithDictionaryHandle();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
//JWT
app.UseAuthentication();
//JWT
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
await app.UseOcelot();
}
}
}
The compiler is throwing error at AddCacheManager line and the error message is:
Error CS0411 The type arguments for method 'ServiceCollectionExtensions.AddCacheManager<T>(IServiceCollection, IConfiguration, string, Action<ConfigurationBuilder>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Please help. Thank you.
we have to add using Ocelot.Cache.CacheManager;

Missing startup.cs program.cs .Net Core Razor

I have a .Net Core 3 Web App using Razor pages. I was messing with solution explorer a few days ago and now I notice I'm missing startup.cs and program.cs. How can I restore them? I'm also getting this error: "Unable to run your project. The RunCommand property is not defined".
First I'd check to make sure your files are in the project directory before trying to rebuild them. If they are still in the directory you can add them to your solution using Visual Studio.
Right click the project > Add > Existing item...
If you don't have those files and can't find them, then recreate them. Here's the default code for them.
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace NOCng
{
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.AddRazorPages();
}
// 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.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace NOCng
{
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>();
});
}
}

Resources