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

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}"
}
}
}

Related

Azure Managed ID: how to convert azure function from connection string to managed id

I have an Azure function that looks like this:
[FunctionName("CreateWidgetWorkspace")]
public async Task<IActionResult> CreateWidgetWorkspace(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "widget/workspaces")] HttpRequest req,
[Queue("widgetworkspaces"), StorageAccount("WidgetStorageQueue")] ICollector<string> messageQueue,
ILogger log)
{
WorkspaceResponse response = new WorkspaceResponse();
var content = await new StreamReader(req.Body).ReadToEndAsync();
log.LogInformation($"Received following payload: {content}");
var workspaceRequest = JsonConvert.DeserializeObject<Workspace>(content);
if (workspaceRequest.name != null){
messageQueue.Add(JsonConvert.SerializeObject(workspaceRequest));
}
else {
response.status = "Error: Invalid Request";
response.requestId=null;
}
return new OkObjectResult(JsonConvert.SerializeObject(response));
}
Everythings works well - the connection string is defined in my local.settings.json file like this:
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"WidgetStorageQueue":
"DefaultEndpointsProtocol=https;AccountName=accountname;AccountKey=asdf+asdf+AStRrziLg=="
}
}
But now i've created a managed Identity and it has been assigned "Contributor" role on all resources inside the resource group.
So I need to refactor this code to no longer use the connection string in local.settings / environment variables. But to use the managed id.
Can you point me to an article or video that would put me on the right path?
I actually prefer not to Azure key vault if possible.
Thanks.
EDIT 1
I've added the 2 packages referenced in the answer. This is what I have in my csproj file:
<ItemGroup>
<PackageReference Include="Azure.Data.Tables" Version="12.4.0" />
<PackageReference Include="Azure.Storage.Queues" Version="12.10.0" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.Webjobs.Extensions.ServiceBus" Version="5.2.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage.Queues" Version="5.0.1" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
</ItemGroup>
And this is what my local.settings.json file looks like:
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "dotnet","WidgetStorageQueue__queueServiceUri":"https://mystorageaccountname.queue.core.windows.net"
},
"ConnectionStrings": {}
}
But I'm getting an error :
2022-05-05T19:30:00.774Z] Executed 'CreateWidgetWorkspace' (Failed, Id=asdf-a22b-asdf-asdf-asdf, Duration=6356ms)
[2022-05-05T19:30:00.777Z] System.Private.CoreLib: Exception while executing function: CreateWidgetWorkspace. Azure.Storage.Queues: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:asdf-8003-asdf-asdf-asdf
Time:2022-05-05T19:30:00.7494033Z
[2022-05-05T19:30:00.781Z] Status: 403 (Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.)
[2022-05-05T19:30:00.782Z] ErrorCode: AuthenticationFailed
[2022-05-05T19:30:00.784Z]
[2022-05-05T19:30:00.785Z] Additional Information:
[2022-05-05T19:30:00.788Z] AuthenticationErrorDetail: Issuer validation failed. Issuer did not match.
[2022-05-05T19:30:00.790Z]
[2022-05-05T19:30:00.791Z] Content:
[2022-05-05T19:30:00.793Z] <?xml version="1.0" encoding="utf-8"?><Error><Code>AuthenticationFailed</Code><Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:asdf-8003-asdf-asdf-asdf
Time:2022-05-05T19:30:00.7494033Z</Message><AuthenticationErrorDetail>Issuer validation failed. Issuer did not match.</AuthenticationErrorDetail></Error>
[2022-05-05T19:30:00.795Z]
[2022-05-05T19:30:00.796Z] Headers:
[2022-05-05T19:30:00.797Z] Server: Microsoft-HTTPAPI/2.0
[2022-05-05T19:30:00.801Z] x-ms-request-id: asdf-asdf-asdf-asdf-60671b000000
[2022-05-05T19:30:00.802Z] x-ms-error-code: AuthenticationFailed
[2022-05-05T19:30:00.809Z] Date: Thu, 05 May 2022 19:29:59 GMT
[2022-05-05T19:30:00.810Z] Content-Length: 422
[2022-05-05T19:30:00.811Z] Content-Type: application/xml
[2022-05-05T19:30:00.812Z] .
Here's my Azure Resource Group:
Here's the function app - you can see I have assigned a user-assigned managed identity to it:
And here are the RBAC roles assigned my managed identity:
Questions
Based on my limited knowledge / reading, it feels like I should install Azure.Identity and create some sort of DefaultAzureCredential?
https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme#specifying-a-user-assigned-managed-identity-with-the-defaultazurecredential
EDIT 2
The changes suggested in the answer basically work. To clarify, the setting in local.setting.json that actually works is this:
"[nameofConnectioninC#Method]__serviceUri":"https://[nameOfStorageAccount].queue.core.windows.net/"
This fails when you local debug, but when you publish everything, upstream tests work.
To use Identity-based connections with Queue Storage, you will need to:
Update you application to use these Nuget Packages: Azure.Storage.Queues and Microsoft.Azure.WebJobs.Extensions.Storage.Queues.
Create an app settings called <CONNECTION_NAME_PREFIX>__serviceUri:
The data plane URI of the queue service to which you are connecting, using the HTTPS scheme.
https://<storage_account_name>.queue.core.windows.net
So in your case you need to create a setting called WidgetStorageQueue__serviceUri
Grant permission to your function app identity to access queue storage. If you just need to send message to a queue, you could use the Storage Queue Data Message Sender role.
I've created a small function app that reproduces this use case.
csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Storage.Queues" Version="12.9.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage.Queues" Version="5.0.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.0" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
function file
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace FunctionApp1
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
[Queue("widgetworkspaces"), StorageAccount("WidgetStorageQueue")] ICollector<string> queueCollector,
ILogger log)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
queueCollector.Add(requestBody);
return new OkObjectResult(requestBody);
}
}
}
settings file
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"WidgetStorageQueue__queueServiceUri": "https://<storage_account_name>.queue.core.windows.net"
}
}

Azure app service diagnostic blob not logging nlog based logs

I want to log nlog generated application logs in app service diagnostic blob [i.e, Application Logging (Blob)
] but only default logs are printed not the nlog based custom logs
but I can print Application Logging (Filesystem) when file target is added to nlog.config. The problem is only with blob.
nlog.config file:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwConfigExceptions="true"
internalLogLevel="info"
internalLogFile="d:\home\LogFiles\temp\internal-nlog-AspNetCore3.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<target xsi:type="Trace" name="String" layout="${level}\: ${logger}[0]${newline} |trace| ${message}${exception:format=tostring}" />
<target xsi:type="Console" name="lifetimeConsole" layout="${level}\: ${logger}[0]${newline} |console| ${message}${exception:format=tostring}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="lifetimeConsole,String" final="true"/>
</rules>
</nlog>
program.cs file
namespace testapp
{
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
logging.AddConsole();
logging.AddDebug();
logging.AddAzureWebAppDiagnostics();
})
.UseNLog() // NLog: Setup NLog for Dependency injection
.ConfigureServices(serviceCollection => serviceCollection
.Configure<AzureBlobLoggerOptions>(options =>
{
options.BlobName = "testlog.txt";
}))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
The Nlog based loggings are not logged in app service diagnostic blob, instead only default logging is printed.
Kindly help to resolve this issue.
Seems that System.Diagnostics.Trace-Target works best for ASP.NET-application and not for ASP.NetCore applications in Azure.
When using AddAzureWebAppDiagnostics it will redirect all output written to Microsoft ILogger to FileSystem or Blob. But any output written to pure NLog Logger-objects will not be redirected.
Maybe the solution is to setup a NLog FileTarget writing to the HOME-directory:
<nlog>
<targets async="true">
<!-- Environment Variable %HOME% matches D:/Home -->
<target type="file" name="appfile" filename="${environment:HOME:cached=true}/logfiles/application/app-${shortdate}-${processid}.txt" />
</targets>
<rules>
<logger name="*" minLevel="Debug" writeTo="appFile" />
</rules>
</nlog>
See also: https://learn.microsoft.com/en-us/azure/app-service/troubleshoot-diagnostic-logs#stream-logs
For including Blob-output then take a look at NLog.Extensions.AzureBlobStorage
Alternative to Blob-output could be ApplicationInsights but it might have different pricing.

Trying to run .net core api which uses swagger from local 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

Deploying Next Js project in IIS

I had a requirement of server side rendering in my project.So, I have developed it using next js and now i got struct in deployment.
I need to deploy my project in iis and dont know how i can achieve that. I tried a lot no luck. It works fine in development mode but not in production.
I tried next export but this is for static pages deployment and
my project uses dynamic pages.
Any help will be appreciated. Thanks in advance.
Try this youtube link it helped me deploy the nextjs app on IIS. Do not forget that you need NodeJS, URLRewrite and IISNode on your server.
You build your nextjs app and deploy it to the IIS folder on the server. You also need the node_modules folder with all the dependencies including express and node.
I have the same problem as you, but so far I have successfully deployed and solved the routing problem, but the only thing that has not been solved is that I cannot redirect to the "NotFound page" (404.js), Maybe we can find a solution together.
This is the current solution :
folder tree :
node_modules
public
pages
index.js
first.js
two.js
_error.js
next.config.js
package.json
package.lock.json
README.md
package.json :
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"prod": "next build && next export"
},
"dependencies": {
"next": "9.3.5",
"react": "16.13.1",
"react-dom": "16.13.1",
}
}
next.config.js :
const data = [
{
path: '/first'
},
{
path: '/two'
}
];
module.exports = {
exportTrailingSlash: true,
exportPathMap: async function () {
//you can get route by fetch
const paths = {
'/': { page: '/' }
};
data.forEach((project) => {
paths[`${project.path}`] = {
page: project.path,
};
});
return paths;
}
}
index.js :
import Link from 'next/link'
import React from 'react';
import Head from 'next/head'
export default function Home(props) {
return (
<div className="container">
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<h1 className="title">
<Link href="/first">
<a>page first</a>
</Link>
<Link href="/two">
<a>page two</a>
</Link>
</h1>
</div>
)
}
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
first.js :
import Link from 'next/link'
import Head from 'next/head'
export default function FirstPost() {
return (
<>
<Head>
<title>First</title>
</Head>
{"First page"}
<h2>
<Link href="/">
<a>Back to home</a>
</Link>
</h2>
</>
)
}
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
two.js :
import Link from 'next/link'
import Head from 'next/head'
export default function FirstPost() {
return (
<>
<Head>
<title>two </title>
</Head>
{"two page"}
<h2>
<Link href="/">
<a>Back to home</a>
</Link>
</h2>
</>
)
}
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
and then run the scripts "prod", you will have /out folder,
just use it as the root directory of IIS,
now test the route :
Enter URL http://{your IP or domain}/ => you will see index.js
Enter URL http://{your IP or domain}/first => you will see first.js
Enter URL http://{your IP or domain}/whatever => you will get 404 error from IIS, and I need the help here!
update the reply,
Finally, I know how to solve it, add web.config and redirect to the 404 errpr page.
note: <action type="Rewrite" url="404/index.html" /> // You can specify the error page here!
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Static Assets" stopProcessing="true">
<match url="([\S]+[.](html|htm|svg|js|css|png|gif|jpg|jpeg))" />
<action type="Rewrite" url="/{R:1}"/>
</rule>
<rule name="ReactRouter Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="404/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

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