Load asset file at Startup failed, file does not exists - asp.net-core

I need to load some asset data to my middleware, but it seems like it can't load the file.
Here's the folder structure:
As you can see, it's already set to "Copy if newer". And the file does get copied over to the bin folder:
Here's the code at ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
var assetFile = Configuration["Assets/Files"];
var testExist = File.Exists(assetFile); // This will be false
//services.AddAsset();
}
Here's the appsettings.json:
{
"Assets": {
"Files": "Assets/something.zip"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
As of now, my only guess is there is file size limit? The .zip file is 165MB large. Just my wild guess, else I don't know why it couldn't find my file.

My guess is that the config setting ins't read properly, that's why it cannot locate the file.
Try replacing this line:
var assetFile = Configuration["Assets/Files"];
with this one:
var assetFile = Configuration["Assets:Files"];
Notice that I used colons to navigate in the appsettings.json keys, instead of a forward slash.

Related

Prevent DefaultAntiforgery from logging errors

Is there a way to stop DefaultAntiforgery from logging errors? I see it takes an ILoggerFactory as parameter, which is a public type, but I don't know how to set it up since DefaultAntiforgery is internal.
I don't think this is a DI issue, but rather a configuration issue. What you want should be possible by configuring logging
Try something like this in your appsettings.json:
{
"Logging": {
// for all logging providers
"LogLevel": {
"Microsoft.AspNetCore.Antiforgery": "None"
},
// or just for the EventLog provider
"EventLog": {
"LogLevel": {
"Microsoft.AspNetCore.Antiforgery": "None"
}
}
}
}

Use serilog save log records

I want to save the printed information to txt text so that we can view important information.
Loggers are created using a LoggerConfiguration object:
Log.Logger = new LoggerConfiguration().CreateLogger();
Log.Information("No one listens to me!");
// Finally, once just before the application exits...
Log.CloseAndFlush();
This is some code I checked the document, I want to save the data in Json format, so that the structure is clear and easy for us to view, what do I need to do, thank you for your suggestions.
Configuring Serilog in ASP.NET Core:
Package:
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
appsettings.json:
{
"Serilog": {
"MinimumLevel": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning"
},
"WriteTo": [
{
"Name": "Console "
},
{
"Name": "File",
"Args": {
"path": "Serilogs\\AppLogs.log",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
}
]
}
}
As shown above, the file receiver requires a parameter, in which we need to specify the log file name and file path. This path can be absolute or relative. Here, I specified a relative path, which will create a folder serilogs in the application folder and write to the file AppLogs.log in that folder.
Then add code in startup.cs to read these Serilog settings in the constructor, as shown below:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
Then change the code in program.cs to specify that Host Builder use Serilog in ASP.NET Core instead of the default logger:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Firstly you need to add a reference to Serilog.Sinks.File via nuget.
The next step is to add the destination for Logger:
.WriteTo.File(new JsonFormatter(), "log.json")
The full listing is:
Log.Logger = new LoggerConfiguration()
.WriteTo.File(new JsonFormatter(), "log.json")
.CreateLogger();
Log.Information("No one listens to me!");
// Finally, once just before the application exits...
Log.CloseAndFlush();
The output in log.json file is:
{"Timestamp":"2022-01-14T02:49:31.5111479+00:00","Level":"Information","MessageTemplate":"No one listens to me!"}
Is it what you need?

Serilog doesn't log to file, only to console

I'm currently working on a mono project and want to use Microsoft.Logging + Serilog there, but I stumble across the following problem:
When I configure Serilog by hand, it logs in both console and the file (if I have configured both parameters). But when I use a configuration file, Serilog always ignores logging to the file.
The configuration file is found and the parameters are read from there, because if I add "Console" there, Serilog logs into the console.
With these settings, Serilog should, as I understand it, log into the console as well as into the file. I'm expecting this log file in "folder with appsettings.json"/logs. But it only logs into the console. And when I delete "Console", it doesn't log anywhere. I don't understand why this is so I am posting a few sections of code that are fundamental. If I have not provided enough information, please write to me in comments under the question.
appsettings.json:
{
"Serilog": {
"Using": [
"Serilog.Sinks.Console"
],
"MinimumLevel": "Debug",
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithProcessId",
"WithThreadId"
],
"WriteTo": [
{
"Name": "File",
"Args": {
"Path": "logs/GUIDemo.log",
"FileSizeLimitBytes": "400000",
"RollingInterval": "Day",
"RetainedFileCountLimit": "15",
"OutputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj} {NewLine}{Exception}",
"shared": true
}
},
"Console"
]
}
}
Here is how I configure Serilog in one class, which methods are executed shortly after the application start:
private IContainer container;
private ILogger<Bootstrapper> logger;
...
public void OnStartup()
{
this.Configuration = this.ConfigureConfiguration();
var builder = new ContainerBuilder();
builder.RegisterModule<AutofacModule>();
this.container = builder.Build();
this.AddLogger();
this.logger = this.container.Resolve<ILogger<Bootstrapper>>();
this.LogApplicationStart();
}
And finally methods AddLogger(), LogApplicationStart() and LogApplicationStart():
private void AddLogger()
{
var loggerFactory = this.container.Resolve<ILoggerFactory>();
loggerFactory.AddSerilog();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(this.Configuration)
.CreateLogger();
}
private IConfigurationRoot ConfigureConfiguration()
{
return new ConfigurationBuilder().SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
}
private void LogApplicationStart()
{
this.logger.LogInformation("App is started");
}
After all of this, the output in the console is (yes, it is Godot):
Mono: Log file is:
'C:\Users\Albert\AppData\Roaming/Godot/mono/mono_logs/2021_01_27 12.46.37(105008).txt'
[12:46:38 INF] App is started
The Mono log file has nothing to do with my log file. I also tried to add Log.CloseAndFlush() at the the end of LogApplicationStart() which is currently the only method in the app, but it didn't help me as well.
Of course, I know there are many similar question here, but I could not find a solution for my problem.

dotnet core logging showing info result always

I am learning .net core logging. I have read some blogs and docs also.
I am wondering why it's showing always "Microsoft.Hosting.Lifetime" Information logs every time with following settings.
{
"Logging": {
"LogLevel": {
"Default": "Error",
"Microsoft": "Error",
"Microsoft.Hosting.Lifetime": "Error",
"DemoWeb.Controllers.HomeController": "Error"
}
},
"AllowedHosts": "*"
}
To double check(If my appsettings.json is working) I added this in ConfigureService.
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(config =>
{
// clear out default configuration
config.ClearProviders();
config.AddConfiguration(Configuration.GetSection("Logging"));
config.AddDebug();
config.AddEventSourceLogger();
config.AddConsole();
});
services.AddControllersWithViews();
}
It's working as expected for my own added "HomeController" Class.
I just want to remove "Microsoft.Hosting.Lifetime" from console logs.
Thanks in advance
Firstly, as #KirkLarkin mentioned, in development, appsettings.Development.json configuration would overwrite values found in appsettings.json.
For more information, you can check : https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#appsettingsjson
want to remove "Microsoft.Hosting.Lifetime" from console logs
In your project, multiple logging providers can be enabled. If you just want to turn off Information level logs about "Microsoft.Hosting.Lifetime" from ConsoleLogger, you can try to apply log filter rule(s) as below.
services.AddLogging(config =>
{
// clear out default configuration
config.ClearProviders();
config.AddConfiguration(Configuration.GetSection("Logging"));
//add log filter for ConsoleLoggerProvider
config.AddFilter<ConsoleLoggerProvider>("Microsoft.Hosting.Lifetime", LogLevel.Error);
config.AddDebug();
config.AddEventSourceLogger();
config.AddConsole();
});
And you can achieve same by configuring logging for that specific provider.
"Console": {
"IncludeScopes": true,
"LogLevel": {
"Microsoft.Hosting.Lifetime": "Error"
}
}

Setup Asp.Net Core app to launch Vue SPA with webpack and HMR

I'm trying to set up a new application using ASP.NET Core 3.0 and Vue. I've been struggling to set it up properly so that the backend and frontend servers are correctly integrated, with proper routing and working HMR. I do have it working now, but I can't tell if this is the correct way do this, and there are some pieces that I don't feel are working as well as they can.
My current setup:
Webpack is configured to output files into wwwroot. I also have HMR and
WriteFilePlugin enabled when running webpack-dev-server:
mode: 'development',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, '../wwwroot'),
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
// write files to fs instead of memory
// so that the server can access and serve index.html
new WriteFilePlugin(),
],
devServer: {
hot: true,
watchOptions: {
poll: true,
},
port: 9001,
},
In Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
.....
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "wwwroot";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
if (env.IsDevelopment())
{
if (System.Diagnostics.Debugger.IsAttached)
{
// run the dev server
endpoints.MapToVueCliProxy("{*path}", new SpaOptions { SourcePath = "ClientApp" },
npmScript: "serve", regex: "Compiled successfully");
}
}
// serve index.html file when no api endpoints are matched
endpoints.MapFallbackToFile("index.html");
}
My problems with this setup:
Typically, HMR builds files in memory, but I have it set up here to write the new files to the file system so that the backend server can access and serve the index.html. This works, but now I have tons of bloat being written to my file system. Is there a way to use the in-memory HMR in conjunction with the ASP.NET server?
The proxying isn't always reliable; I often get errors in the console that it can't connect to the server. Additionally, index.html sometimes gets cached and I have to do a hard reload. Can this be made more reliable somehow?