Trying to run .net core api which uses swagger from local IIS - iis

I created a .Net core web api application and using swagger .I am trying to create a profile for the application to run it on IIS while run the application from visual studio 2019.
Application folder has full permissions and the app pool /website, both are running under service account which has full admin rights.
I am trying to configure the application to use https to run on a specific port 443.Not sure if i have to make any code changes so that application runs on specific port
If i try to run the application using IIS express with the url https://localhost:portnumber/TestApi/swagger.It works beautifully
If i try to use the profile that is configured for IIS to run the application with the url "https://localhost/TestApi/swagger, then its throwing the error.
Below is my web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="bin\IISSupport\VSIISExeLauncher.exe" arguments="-argFile IISExeLauncherArgs.txt" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
<environmentVariables>
<environmentVariable name="ASPNETCORE_HTTPS_PORT" value="44342" />
<environmentVariable name="COMPLUS_ForceENC" value="1" />
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
I have my start up.cs file as follows
public class Startup
{
public Startup(IHostingEnvironment env)
{
//Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
ConfigSettingLayoutRenderer.DefaultConfiguration = 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.AddSingleton<IConfiguration>(Configuration);
services.Configure<IISOptions>(options =>
{
options.AutomaticAuthentication = false;
});
services.AddSwaggerGen(c => c.SwaggerDoc("v1",
new Swashbuckle.AspNetCore.Swagger.Info()
{
Title = "Test APIs",
Description = "REST APIs",
Version = "v1"
})
);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// 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.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "My API");
});
app.Run(async (context) =>
{
context.Response.Redirect("TestApi/swagger");
await Task.FromResult(0);
});
}
}
and my launchsettings.json as below
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iis": {
"applicationUrl": "https://localhost/TestApi",
"sslPort": 0
},
"iisExpress": {
"applicationUrl": "http://localhost:57086/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"PmDashBoard.Api": {
"commandName": "IIS",
"launchBrowser": true,
"launchUrl": "https://localhost/TestApi",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost/TestApi"
}
}
}
I have .Net core hosting bundle is installed on my machine and latest version of VS2019 installed. I am trying Ctrl + F5 to run the application from VS2019 and getting the below error
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Detailed Error Information:
Module
IIS Web Core
Notification
BeginRequest
Handler
Not yet determined
Error Code
0x80070003
Config Error
Cannot read configuration file

Related

Net7 JWT Null Reference when publishing Blazor WASM Project?

so I've been working in the Net7 preview and have been trying to deploy a WASM project with identity and authentication which works fine locally. When I deploy the website 500s and digging into some of the logs, I get:
2022-11-07T13:42:28.854805951Z fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3]
2022-11-07T13:42:28.854856853Z Exception occurred while processing message.
2022-11-07T13:42:28.854865053Z System.NullReferenceException: Object reference not set to an instance of an object.
2022-11-07T13:42:28.856255318Z at Microsoft.AspNetCore.ApiAuthorization.IdentityServer.IdentityServerJwtBearerOptionsConfiguration.ResolveAuthorityAndKeysAsync(MessageReceivedContext messageReceivedContext)
2022-11-07T13:42:28.856286120Z at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
In my Program.cs I have
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
builder.Services.AddAuthentication()
.AddIdentityServerJwt()
.AddJwtBearer()
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = builder.Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
});
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
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.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
I've been trying to follow different Duende guides but even when I eventually get it to run locally, I still get the same error. I've tried removing the JWT lines in AddAuthentication() and that also did not seem to help.
You need to have on your appsettings.json
"IdentityServer": {
"Key": {
"Type": "Development"
} },
Change the type to the correct one.

Azure 500 error on a Blazor Wasm Hosted with Authentication

I am at a complete loss here. I have a Blazor WASM Hosted running .net5 which has been deployed to Azure App Services. When there was no Database there was no problem deploying to Azure. It loaded and ran as expected. I have since installed Identity and a DBContext. Everything builds locally and runs properly with a local SQL instance.
On Azure, I have created a new SQLServer as well as a SQL database. On the SQL Database Firewall Settings i have "Allow Azure Services and resources to access this server" as well as a Rule for my client IP (not the IP for the Azure App).
For the App Service in Configuration i have a ConnectionString named DefaultConnection (same as in appsettings.json) with the same connection string as the SQLDatabase provides, source AppConfig, Type SqlAzure
I am publishing to Azure using the VS2019 Publish on the Server project (the startup project). I chose Target to be Azure -> Azure App Sevices (Windows) and my instance name. Configuration is Release, Target Framework net5.0, DeploymentMode Framework-dependent, Target runtime Portable.
The Service Dependencies is set to AzureSqlDatabase which uses the ConnectionName DefaultConnection, Username and Password are the Admin UserPassword setup for the SQL Server created on Azure and the SaveConnectionStringValue is Azure App Settings. (This auto populates the App Services Configuration ConnectionString described above.
When I click publish I see in the output that all publishes correctly:
Publish Succeeded.
Web App was published successfully http://bbqfriend.azurewebsites.net/
========== Build: 1 succeeded, 0 failed, 6 up-to-date, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========
Installation of Web App Site extension Microsoft.AspNetCore.AzureAppServices.SiteExtension is in progress...
Restarting the Web App...
Successfully installed Web App extension Microsoft.AspNetCore.AzureAppServices.SiteExtension
Successfully restarted Web App.
However when the page launches, It shows a 500 Error.
If I go back to the Publish and Edit the settings - Database - DefaultConnection and Check the Use this Connection string at runtime selecting the connectionstring configured in the ServiceDependencies as well as the EntityFrameworkMigrations DataContext Apply This Migrations on publish. When I publish that profile it will do the migrations as well as the Seeds I have defined within the DataContext OnModelCreating override
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
#region Identity Seed
modelBuilder.ApplyConfiguration(new ApplicationUserConfiguration());
modelBuilder.ApplyConfiguration(new IdentityRoleConfiguration());
modelBuilder.ApplyConfiguration(new IdentityUserRoleConfiguration());
#endregion
//modelBuilder.ApplyConfiguration(new CountryConfiguration());
}
So I know the connection string is correct and there is a Database with the proper model and seeded data. Why am I getting a 500?!?
Here is my appsettings.json in the Server project
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database={DatabaseName};Trusted_Connection=True;MultipleActiveResultSets=true"
},
"IdentityServer": {
"Clients": {
"XXXX.Client": {
"Profile": "IdentityServerSPA"
}
}
},
"Serilog": {
"Using": [ "Serilog.Sinks.MSSqlServer" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.Authorization.DefaultAuthorizationService": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"System": "Warning",
"System.Net.Http.HttpClient*": "Warning",
"IdentityServer4": "Warning",
"Serilog.AspNetCore": "Warning"
}
},
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "DefaultConnection",
"sinkOptionsSection": {
"tableName": "Logs"
},
"columnOptionsSection": {
"additionalColumns": [
{
"ColumnName": "InstanceId"
},
{
"ColumnName": "Origin"
},
{
"ColumnName": "SourceContext"
},
{
"ColumnName": "UserId"
},
{
"ColumnName": "Username"
}
],
"excludeAdditionalProperties": true
}
}
}
]
},
"AllowedHosts": "*"
}
Here is the Startup.cs for the Server project
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)
{
//Register the Datacontext and Connection String
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
//Sets up the default Asp.net core Identity Screens - Use Identity Scaffolding to override defaults
services.AddDefaultIdentity<ApplicationUser>( options =>
{
options.SignIn.RequireConfirmedAccount = true;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequiredUniqueChars = 0;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 8;
options.User.RequireUniqueEmail = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DataContext>();
//Associates the User to Context with Identity
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, DataContext>( options =>
{
options.IdentityResources["openid"].UserClaims.Add(JwtClaimTypes.Role);
options.ApiResources.Single().UserClaims.Add(JwtClaimTypes.Role);
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove(JwtClaimTypes.Role);
//Adds authentication handler
services.AddAuthentication().AddIdentityServerJwt();
//Register Repositories for Dependency Injection
services.AddScoped<ICountryRepository, CountryRepository>();
services.AddControllersWithViews();
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, DataContext dataContext)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
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();
}
//AutoMigrates data
//dataContext.Database.Migrate();
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseSerilogIngestion();
app.UseSerilogRequestLogging();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
}
Here is the Program.cs for the Server project
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.WithProperty("InstanceId", Guid.NewGuid())
.Enrich.WithProperty("Origin", "Server")
.CreateLogger();
try
{
Log.Information("Starting up");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Here is the Program.cs for the Client project
public static async Task Main(string[] args)
{
//Serilog
var levelSwitch = new LoggingLevelSwitch();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.Enrich.WithProperty("InstanceId", Guid.NewGuid())
.Enrich.FromLogContext()
.WriteTo.BrowserHttp(controlLevelSwitch: levelSwitch)
.CreateLogger();
Log.ForContext<Program>().Information("Client has started");
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddLogging(logging =>
{
logging.ClearProviders();
logging.AddSerilog(dispose: true);
});
builder.Services.AddHttpClient("XXX.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddTransient(sp =>
sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("XXXX.ServerAPI"));
builder.Services.AddApiAuthorization()
.AddAccountClaimsPrincipalFactory<RolesClaimsPrincipalFactory>();
//Register Services
var baseAddress = new Uri($"{builder.HostEnvironment.BaseAddress}api/");
void RegisterTypedClient<TClient, TImplementation>(Uri apiBaseUrl)
where TClient : class where TImplementation : class, TClient
{
builder.Services.AddHttpClient<TClient, TImplementation>(client => client.BaseAddress = apiBaseUrl)
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
}
RegisterTypedClient<ICountryService, CountryService>(baseAddress);
await builder.Build().RunAsync();
}
I do have Serilog configured and it looks to be working as well. Here are the error messages I am seeing during the Server Launch
System.InvalidOperationException: Startup assembly Microsoft.ApplicationInsights.StartupBootstrapper failed to execute. See the inner exception for more details.
---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.ApplicationInsights.StartupBootstrapper, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
File name: 'Microsoft.ApplicationInsights.StartupBootstrapper, Culture=neutral, PublicKeyToken=null'
at System.Reflection.RuntimeAssembly.InternalLoad(ObjectHandleOnStack assemblyName, ObjectHandleOnStack requestingAssembly, StackCrawlMarkHandle stackMark, Boolean throwOnFileNotFound, ObjectHandleOnStack assemblyLoadContext, ObjectHandleOnStack retAssembly)
at System.Reflection.RuntimeAssembly.InternalLoad(AssemblyName assemblyName, RuntimeAssembly requestingAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.ExecuteHostingStartups()
--- End of inner exception stack trace ---
and
System.InvalidOperationException: Startup assembly DiagnosticServices.HostingStartup failed to execute. See the inner exception for more details.
---> System.IO.FileNotFoundException: Could not load file or assembly 'DiagnosticServices.HostingStartup, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
File name: 'DiagnosticServices.HostingStartup, Culture=neutral, PublicKeyToken=null'
at System.Reflection.RuntimeAssembly.InternalLoad(ObjectHandleOnStack assemblyName, ObjectHandleOnStack requestingAssembly, StackCrawlMarkHandle stackMark, Boolean throwOnFileNotFound, ObjectHandleOnStack assemblyLoadContext, ObjectHandleOnStack retAssembly)
at System.Reflection.RuntimeAssembly.InternalLoad(AssemblyName assemblyName, RuntimeAssembly requestingAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.ExecuteHostingStartups()
--- End of inner exception stack trace ---
UPDATE
I am able to replicate the above error messages and they are logged into the Database via Serilog.
So we can see the "Starting up" from the Server Program.cs Main method (above) and the next entry is from the EntityFramework Model Validation. Then comes the errors. I can see the Namespace as Microsoft.AspNetCore.Hosting.Diagnostics as the source of the exception.
I attempted to add a Nuget reference but that did nothing
I attempted to add a reference to added services.AddApplicationInsightsTelemetry(); to the Server Startup.cs ConfigureServices and the ApplicationInsights InstrumentationKey to the appsettings.json (which already existed within Azure as a Variable) but that did nothing
I added a reference to and added
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseAzureAppServices();
});
as per a workaround found here https://github.com/dotnet/extensions/issues/2566 which did not help
Update Day 2
Adding more information as I am still getting the same exceptions. Im curious if this is a compatibility issue between versions. My application is .net5 and running on Azure using .net5 early access.
Here are my Nuget packages for the Server Project
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="5.0.1" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.ApiAuthorization.IdentityServer" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.1" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.AspNetCore.Ingestion" Version="1.0.0-dev-00012" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.6.0" />
</ItemGroup>
Here are the Nuget Packages for the Client project
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.BrowserHttp" Version="1.0.0-dev-00012" />
<PackageReference Include="System.Net.Http.Json" Version="5.0.0" />
</ItemGroup>
I have tried removing Serilog from both the Client and Server projects. I still received a 500.
With Serilog Removed I tried using .UseAzureAppServices() from https://github.com/dotnet/extensions/issues/2566 with no luck as well.
I did notice an additional error messsage
2021-01-06 19:00:38.322 +00:00 [Error] Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware: An unhandled exception has occurred while executing the request.
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Extensions.DependencyInjection.IdentityServerBuilderConfigurationExtensions.<>c.<AddSigningCredentials>b__10_2(IServiceProvider sp)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at ... (removed for post size)
I have been able to isolate this to becoming an issue when I deployed my site as a Blazor WebAssembly Hosted solution. I was able to get a version of my site which was upgraded to .net5 PRE switching from Blazor WebAssembly to Blazor WebAssembly Hosted. The .net5 version was able to be deployed to Azure without issues. When deploying the WebAssembly Hosted version is when I got 500 Errors. So this has to do with deploying a Blazor WebAssembly Hosted solution to Azure.
I also experimented by creating an out of the box Blazor WebAssembly Hosted solution without Authentication and deployed it to Azure. This works with no issues. HOWEVER, when I create an out of the box Blazor WebAssembly Hosted WITH Authentication (individual user accounts stored in app) and deployed it to Azure it fails with 500!
The easiest way to make it work:
Add/set the env variable ASPNETCORE_ENVIRONMENT to Development
...and your Hosted Blazor WASM with Identity will finally work in Azure App Service
If you don't want the easy way above, do these instead:
Generate a self-signed certificated by following this article:
(in the Generating a Self-Signed Certificate section)
https://gavilan.blog/2020/08/18/blazor-using-a-self-signed-certificate-for-identityserver4-in-azure-app-service/
Remember the password you used for the generated certificate.
Place the certificate in your project (e.g. in the server project)
Append these in the appsettings.json file:
Publish the app once again.

Microsoft Chatbot -"There was an error sending this message to your bot: HTTP status code Forbidden" after deploying on Azure

I am building a chatbot on Bot Framework 4 on .NetCore2.2. The chatbot has LUIS, QnA Maker integrated in it and it works perfectly fine locally in Emulator with and without security (Microsoft APP ID/ Password). After I deploy it on Azure using Azure DevOps it gives me the error below:
I have followed the instructions here. It works fine locally but not after deployment on Azure.
Here is my appsetting.json.
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"botFilePath": "nlp-with-dispatch.bot",
"botFileSecret": "",
"MicrosoftAppId": "a8402bb0-3a7a-4727-a2b1-e8012b009732",
"MicrosoftAppPassword": "<password here>",
"QnAKnowledgebaseId": "55c79164-f0f1-4b4e-ab7e-1a5481227683",
"QnAEndpointKey": "<key here>",
"QnAEndpointHostName":
"https://<name>.azurewebsites.net/qnamaker",
"LuisAppId": "44d2cf32-153d-4d57-b5ac-30e34be7faa3",
"LuisAPIKey": "<key here>",
"LuisAPIHostName": "westus",
"AllowedHosts": "*"
}
EDIT 1: I am getting the following in browser console when I try to test from Test in Web Chat.
EDIT 2:
When I add Microsoft APP ID and Password in Emulator when working on localhost, my bot gets Authentication error in Emulator.
EDIT 3: This is the exception I am getting
POST to CivicTheBot failed: POST to the bot's endpoint failed with HTTP status 403 System.Exception at Microsoft.Bot.ChannelConnector.BotAPI.ThrowOnFailedStatusCode
EDIT 4:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.BotFramework;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Extensions.DependencyInjection;
using IntermediatorBotSample.Middleware;
using Microsoft.Extensions.Configuration;
using Microsoft.Bot.Builder.Core.Extensions;
using System;
using Microsoft.Bot.Builder.TraceExtensions;
namespace Microsoft.BotBuilderSamples
{
public class Startup
{
public IConfiguration Configuration
{
get;
}
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true,
reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion
(CompatibilityVersion.Version_2_1);
// Create the Bot Framework Adapter with error handling enabled.
services.AddSingleton<IBotFrameworkHttpAdapter,
AdapterWithErrorHandler>();
// Create the bot services (LUIS, QnA) as a singleton.
services.AddSingleton<IBotServices, BotServices>();
// Create the bot as a transient.
services.AddTransient<IBot, DispatchBot>();
// Create the User state.
services.AddSingleton<UserState>();
services.AddMvc().AddControllersAsServices();
services.AddSingleton(_ => Configuration);
services.AddBot<DispatchBot>(options =>
{
// options.CredentialProvider = new
ConfigurationCredentialProvider(Configuration);
options.Middleware.Add(new CatchExceptionMiddleware<Exception>(async
(context, exception) =>
{
await context.TraceActivityAsync("Bot Exception",
exception);
await context.SendActivityAsync($"Sorry, it looks like
something went wrong: {exception.Message}");
}));
// Handoff middleware
options.Middleware.Add(new HandoffMiddleware(Configuration));
});
services.AddMvc(); // Required Razor pages
}
// 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.UseDefaultFiles();
app.UseStaticFiles();
app.UseBotFramework();
//app.UseHttpsRedirection();
app.UseMvc();
}
}
}

Azure LetsEncrypt cannot access .well-known/acme-challenge for my function

I am trying to enable SSL for my azure function using the letsencrypt site-extension for azure as described here. I was following the instructions in that wiki and on this website.
However, I get an error when it tries to verify the website.
The error indicates that the acme-challenge page cannot be accessed (404).
This is my web.config under .well-known/:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<clear />
<add name="ACMEStaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
</handlers>
<staticContent>
<remove fileExtension="." />
<mimeMap fileExtension="." mimeType="text/plain" />
</staticContent>
</system.webServer>
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</configuration>
Does anyone have any ideas on what could be going wrong?
Here's how you can do that.
In your function app, create a new proxy for the challenge directory (this is required as the challenge will be a http get to /.well-known/acme-challenge/, and per default a function in a function app will only answer on /api/.
You can setup the proxy in the following way.
proxies.json
{
"$schema": "http://json.schemastore.org/proxies",
"proxies": {
"LetsEncryptProxy": {
"matchCondition": {
"route": "/.well-known/acme-challenge/{code}"
},
"backendUri": "http://%WEBSITE_HOSTNAME%/api/letsencrypt/.well-known/acme-challenge/{code}"
}
}
}
The important setting here is the Route Template: /.well-known/acme-challenge/{*rest} this will match all request that goes to the challenge directory.
Please note that proxies are a preview feature and you have to enable it, for it to work.
Reference:
https://github.com/sjkp/letsencrypt-siteextension/wiki/Azure-Functions-Support
https://blog.bitscry.com/2018/07/06/using-lets-encrypt-ssl-certificates-with-azure-functions/
I figured it out:
Similar to KetanChawda-MSFT's answer, except the proxy needs to hit the api endpoint function that you create.
So here's the function:
// https://YOURWEBSITE.azurewebsites.net/api/letsencrypt/{code}
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, string code, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. {code}");
var content = File.ReadAllText(#"D:\home\site\wwwroot\.well-known\acme-challenge\"+code);
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(content, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
And here's the proxy that hits that function when letsEncrypt tries to verify the acme challenge:
{
"$schema": "http://json.schemastore.org/proxies",
"proxies": {
"LetsEncryptProxy": {
"matchCondition": {
"route": "/.well-known/acme-challenge/{code}"
},
"backendUri": "http://%WEBSITE_HOSTNAME%/api/letsencrypt/{code}"
}
}
}

No data in application-insights when deployed on Azure

I have a .net core 2 MVC web application that uses application insights on Azure.
I also configured nlog to trace with application insights.
Everything works on my pc, as I found exceptions and tracing on azure, but when I deploy the application and use it on azure it doesn't generates any event on application insights (I found only the events in the log file).
So I tried to create an instance of TelemetryClient in a controller and it works even in the the deployed instance:
TelemetryClient tc = new TelemetryClient()
{
InstrumentationKey = "11111111-2222-3333-4444-555555555555"
};
tc.Context.User.Id = Environment.MachineName;
tc.Context.Session.Id = "session_id";
tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
tc.TrackTrace("Privacy page says hello with TelemetryClient");
Here are the snippets of my project:
appsettings.json
{
"ApplicationInsights": {
"InstrumentationKey": "11111111-2222-3333-4444-555555555555"
}
}
appsettings.Staging.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=tcp:dom.database.windows.net,1433;Initial Catalog=dom;Persist Security Info=False;User ID=user;Password=pass;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
},
"AllowedHosts": "*",
"Logging": {
"LogLevel": {
"Default": "Trace",
"System": "Information",
"Microsoft": "Information"
}
}
}
I defined the same ASPNETCORE_ENVIRONMENT value on my VS and on Azure (Staging) to be sure to load the same appsettings and deployed all the files.
I load the configuration in this way
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
CreateWebHostBuilder is this
public static IWebHostBuilder CreateWebHostBuilder(string[] args, IConfiguration config) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext) =>
{
//config.AddJsonFile("appsettings.json");
})
.UseStartup<Startup>()
.ConfigureLogging(
logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseApplicationInsights() // Enable Application Insights
.UseNLog();
nlog.config contains
<extensions>
<add assembly="Microsoft.ApplicationInsights.NLogTarget" />
</extensions>
<targets>
<target type="ApplicationInsightsTarget" name="aiTarget" />
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Warn" writeTo="aiTarget" />
<logger name="*" minlevel="Warn" writeTo="f" />
</rules>
It seems to me that something is wrong in the configuration or the InstrumentationKey, but I don't know how to inspect it.
Any idea, or... is there any way to know how the application insights library is configured in order to find some useful info to solve the problem? I tried with the remote debugging but I have no idea of what inspect.
Based on your description, I think you have set another application insights key in azure portal -> your web application -> configuration-> application settings.
Please check if you did this or not:
If the key is there, you need remove it. Or put this line of code AddEnvironmentVariables() before the AddJsonFile(), like below:
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables() //put this before AddJsonFile()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json", optional: true)
.Build();
Please let me know if you have more issues.

Resources