In the kestrel part of my BuildWebHost, I can verify that the url is set to https://localhost/5000. However, when host.run() is called, only https://localhost is launched for some reason.
`
.UseKestrel(options =>
{
X509Certificate2 certificate = null;
if (!string.IsNullOrEmpty(certFileName) && !string.IsNullOrEmpty(certPassword))
{
certificate = new X509Certificate2(certFileName, certPassword);
url = "https://localhost:5000";
}
options.Listen(IPAddress.Loopback, 5000, listenOptions =>
{
if (certificate != null)
{
listenOptions.UseHttps(certificate);
}
});
})
`
Additional Information:
It's launched when I run Visual Studio Code. My configurations files all say localhost:5000 This used to work. I changed my program property in launch.json to point at net2.0 path and that's when it stopped.
launch.json contents:
`
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
// "program": "${workspaceFolder}/bin/Debug/netcoreapp1.1/TennisFolderAPI.dll",
"program": "${workspaceFolder}/bin/Debug/netcoreapp2.0/TennisFolderAPI.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"launchBrowser": {
"enabled": true,
"args": "${auto-detect-url}",
"windows": {
"command": "cmd.exe",
"args": "/C start ${auto-detect-url}"
},
"osx": {
"command": "open"
},
"linux": {
"command": "xdg-open"
}
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
},
"requireExactSource": false,
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
`
For Visual Studio in launchSettings.json use "launchUrl": "http://localhost:5000".
Launch.json is for Visual Studio Code.
https://www.google.com/amp/s/andrewlock.net/how-to-set-the-hosting-environment-in-asp-net-core/amp/
Related
How can i set ApplicationInsights to send Ilogger _logger messages.
Now i see every log at Console and in files, but in azure i don't see my own Logs.
I tried a lot of things and maybe the information is here:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-monitoring
But i don't find it. :(
Thanks for helping.
In Program.cs:
var _logger = new LoggerConfiguration().CreateBootstrapLogger();
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((context, services, loggerConfiguration) => loggerConfiguration
.ReadFrom
.Configuration(builder.Configuration)
.Enrich
.FromLogContext());
Bootstrap.ConfigureServices(builder.Services, builder.Configuration, builder.Environment);
var app = builder.Build();
Bootstrap.ConfigureWebApp(app);
app.Run();
In appsettings.json:
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File",
"Serilog.Sinks.ApplicationInsights"
],
"MinimumLevel": {
"Default": "Debug"
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"Path": "../Logs/MyLog-.json",
"RollingInterval": "Day",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
},
{
"Name": "File",
"Args": {
"Path": "../Logs/MyLog-.log",
"RollingInterval": "Day",
//"OutputTemplate": "[({Component}|{MachineName}|{ThreadId}) {Timestamp:G} [{Level:u3}]{Message:lj}{NewLine}{Exception} ]"
}
},
{
"Name": "ApplicationInsights",
"Args": {
"ConnectionString": "[MyCONNECTIONSTRING]",
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
}
}
]
},
This is the content of my tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"/Crm/AdminApi/Api.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": ""
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"/Crm/AdminApi/Api.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": ""
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"/Crm/AdminApi/Api.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": ""
}
]
}
The problem is that when I run it using F5 it fails because it runs as the vscode user I guess.
Also when I run dotnet build from inside the VS Code terminal, it does not work.
However, when I run sudo dotnet build in the VS Code terminal, or when I run dotnet build from a root bash terminal, it works.
How can I force VS Code to run my code as the root user? I tried "command": "sudo dotnet" but it did not work.
Project is using .Net Core 3.1 WebAPI.
I am trying to log IP address of the client's device to console. I have installed this package Serilog.Enrichers.ClientInfo v1.2.0 and followed their steps.
In addition to console, there is a table ErrorLog with column [ClientIp] where I would like to log the IP address.
As you can see in the output, both ClientIp and ClientAgent sections are blank.
Am I missing something? Also please verify if the syntax is correct.
Here is my Serilog config from appsettings.json
"Serilog": {
"using": [],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithClientIp", "WithClientAgent" ],
"WriteTo": [
{
"Name": "Logger",
"Args": {
"configureLogger": {
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Level:u3} {Timestamp:o}] {ClientIp} {ClientAgent} ({SourceContext}) {Message} {NewLine}"
}
}
]
}
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "#l in ['Error', 'Fatal']"
}
}
],
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "TestDbContext",
"tableName": "ErrorLogs",
"batchPostingLimit": 50,
"autoCreateSqlTable": true,
"columnOptionsSection": {
"removeStandardColumns": [ "MessageTemplate" ],
"customColumns": [
{
"ColumnName": "ClientIp",
"DataType": "VARCHAR",
"AllowNull": true,
"DataLength": 50
//"NonClusteredIndex": true
}
]
}
}
}
]
}
}
}
]
}
Output:
[INF 2022-07-11T20:13:49.0041535+05:30] () APP:API service has
started
[INF 2022-07-11T20:13:49.5737570+05:30]
(Microsoft.Hosting.Lifetime) Now listening on:
"https://localhost:7017"
[INF 2022-07-11T20:13:49.5987755+05:30]
(Microsoft.Hosting.Lifetime) Now listening on:
"http://localhost:5017"
[INF 2022-07-11T20:13:49.6185554+05:30]
(Microsoft.Hosting.Lifetime) Application started. Press Ctrl+C to
shut down.
[INF 2022-07-11T20:13:49.6255005+05:30]
(Microsoft.Hosting.Lifetime) Hosting environment: "Development"
[INF 2022-07-11T20:13:49.6305270+05:30]
(Microsoft.Hosting.Lifetime) Content root path: "****"
[ERR 2022-07-11T20:14:29.2967601+05:30] () Testing exception
[ERR 2022-07-11T20:14:29.3735005+05:30]
(Serilog.AspNetCore.RequestLoggingMiddleware) HTTP "GET"
"/api/Hospitals" responded 500 in 970.4728 ms
Try this package serilog-aspnetcore:
app.UseSerilogRequestLogging(options =>
{
// Customize the message template
options.MessageTemplate = "{RemoteIpAddress} {RequestScheme} {RequestHost} {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";
// Emit debug-level events instead of the defaults
options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;
// Attach additional properties to the request completion event
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
diagnosticContext.Set("RemoteIpAddress", httpContext.Connection.RemoteIpAddress);
};
});
Check on this link, it might help.
Adding IP logging #38
It looks like you are missing "Serilog.Enrichers.ClientInfo" in your using statement (appsettings.json ln 2).
I'm developing a web app with C#. Whenever I run the application using Visual Studio, two browser tabs open and the application runs on two ports: one of them is the correct one - the one with a portnumber that I specified. The other is unwanted and its portnumber is different every time I run it (I think VS looks at the next available port).
Does anyone know where the latter can be configured? I only want the application to run on the specified portnumber.
This is part of launchSettings.json where I've specified the sslPort:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:44646",
"sslPort": 44368
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Cassys.App": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
The port 44368 works and is correct. But somehow another browser-tab is opened with a different portnumber every time.
Edit: as requested by #Zhi Lv in comment section, here's the launch.json:
{
linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/WebApi.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"env": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_URLS": "localhost:44368"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
When I click 'Start Debugging' in visual code I receive this error. No google results have worked so how do I fix it? I'm trying to compile C# code.
The preLaunchTask 'build' terminated with exit code 1.
I have added some code below of my launch.json file and the other file for my VS code as I wasn't sure if it would help being able to see them.
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceRoot}/bin/Debug/<target-framework>/<project-name.dll>",
"args": [],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"console": "internalConsole"
},
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceRoot}/bin/Debug/<target-framework>/<project-name.dll>",
"args": [],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"launchBrowser": {
"enabled": true,
"args": "${auto-detect-url}",
"windows": {
"command": "cmd.exe",
"args": "/C start ${auto-detect-url}"
},
"osx": {
"command": "open"
},
"linux": {
"command": "xdg-open"
}
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceRoot}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
tasks.json:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "dotnet",
"isShellCommand": true,
"args": [],
"tasks": [
{
"taskName": "build",
"args": [ ],
"isBuildCommand": true,
"showOutput": "silent",
"problemMatcher": "$msCompile"
}
]
}
There's a preLaunchTask configured in your launch.json file. It is the task that gets run before the script is executed. That task is 'build', from your tasks.json file. It is failing, as indicated by its return of a non-zero error code. You need to open up your tasks.json configuration file, see what the 'build' task entails, and then figure out why it is failing.