InvalidOperationException: Could not find 'UserSecretsIdAttribute' on assembly - asp.net

After deploying ASP.NET Core app to azure and opening the site, I get the following error:
InvalidOperationException: Could not find 'UserSecretsIdAttribute' on
assembly '******, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null'.
The exception details also include that the error happens at Startup.cs on this line of code:
builder.AddUserSecrets();
Thank you

There was an update to the user secrets module just recently. Version 1.0.1 and up now requires you specify an assembly-level attribute for the id of the user secrets, or as a fallback, the way it was previously in project.json.
Here is the announcement on GitHub: https://github.com/aspnet/Announcements/issues/209
You can define the secrets id in the .csproj like this:
<PropertyGroup>
<UserSecretsId>aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed</UserSecretsId>
</PropertyGroup>
This generates the following assembly-level attribute. Alternatively, instead of adding it in the .csproj file, you can of course add it yourself e.g. to Startup.cs:
[assembly: UserSecretsId("aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed")]
Also, you should use:
builder.AddUserSecrets<Startup>();
It will search for that attribute in the assembly of the given type, in this case I used the Startup class.
Note: this will be deprecated in 2.0: (1.0.2 and 1.1.1 have marked it obsolete)
builder.AddUserSecrets();
I checked the source code for the user secrets configuration, and calling AddUserSecrets() without the type does this:
var attribute = entryAssembly.GetCustomAttribute<UserSecretsIdAttribute>();
if (attribute != null)
{
return AddUserSecrets(configuration, attribute.UserSecretsId);
}
// try fallback to project.json for legacy support
try
{
var fileProvider = configuration.GetFileProvider();
return AddSecretsFile(configuration, PathHelper.GetSecretsPath(fileProvider));
}
catch
{ }
// Show the error about missing UserSecretIdAttribute instead an error about missing
// project.json as PJ is going away.
throw MissingAttributeException(entryAssembly);
It's trying to find the UserSecretsId attribute on your assembly, and failing that, checking if it could find it in project.json. Then (as commented) returns an error about the missing attribute as they wouldn't want to complain about project.json anymore as it is being deprecated.

I want to add to this answer, for those in my situation.
I am writing a .NET Core console app, trying to use the secrets manager (not sure it's meant for console apps). The only way I was able to rid myself of the error was using the assembly level attribute on the assembly where I was using the secrets manager.
As I said, I am not sure if the secrets manager is meant for console apps. So maybe there is an issue with .xproj files vs. .csproj files.

My .NET Core 3.1 Worker Service required additional setup (more than a Web project).
In Program.cs in the CreateHostBuilder method I needed this:
.ConfigureAppConfiguration((ctx, builder) =>
{
// enable secrets in development
if (ctx.HostingEnvironment.IsDevelopment())
{
builder.AddUserSecrets<Worker>();
}
})
But (unlike my Web project) I explicitly needed to add this nuget package:
install-package Microsoft.Extensions.Configuration.UserSecrets
After that I could access secrets.

Related

Why does a force downgrade causes an assembly load exception in .Net Core?

I have a sample solution with a console and library project. Both reference the same nuget but a different version. The console project also has a reference to the library project. So the structure is like this:
- Solution
- ConsoleApp
- Project Reference: Library
- Nuget: NServiceBus.RabbitMQ (5.2.0)
- Library
- Nuget: NServiceBus.RabbitMQ (6.0.0)
You can find the solution here.
Since Nuget uses the nearest wins rule, the nuget package that gets resolved is version 5.2.0. This is what I want, so far so good. But when I run the application and run a method of the Library I get the following exception:
Could not load file or assembly 'NServiceBus.Transport.RabbitMQ, Version=6.0.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
In .NET Framework I would solve this with an assembly redirect. But that isn't available in .Net Core. I always thought that .Net Core solves this automatically by using the deps.json file. There I see the following statement:
"Library/1.0.0": {
"dependencies": {
"NServiceBus.RabbitMQ": "5.2.0"
},
"runtime": {
"Library.dll": {}
}
}
But still at runtime he tries to resolve the 6.0.0 version. I'm using the latest .Dot Net 3.1.X SDK.
I'm I doing something wrong or does this seem like a bug?
For the record, this is a simple sample project. The actual situation where I need this is much more complex. I also do understand that doing this can cause runtime exceptions while running the application.
It appears to be by design.
A little bit of searching, I found this: https://github.com/dotnet/fsharp/issues/3408#issuecomment-319466999
The coreclr will load an assembly of the version or higher than the reference. If the assembly discovered is lower than the reference then it fails.
Also this: https://github.com/dotnet/sdk/issues/384#issuecomment-260457776
downgrading the assembly version isn't supported on .NET Core
So, to confirm, I spent much more time than I intended looking/searching through https://github.com/dotnet/runtime. Eventually I found the assembly version compatibility method: https://github.com/dotnet/runtime/blob/172059af6623d04fa0468ec286ab2c240409abe3/src/coreclr/binder/assemblybindercommon.cpp#L49-L53
It checks all the components of the version separately, but if we look at just one, we can see what it's doing:
if (!pFoundVersion->HasMajor() || pRequestedVersion->GetMajor() > pFoundVersion->GetMajor())
{
// - A specific requested version component does not match an unspecified value for the same component in
// the found version, regardless of lesser-order version components
// - Or, the requested version is greater than the found version
return false;
}
As the comment says, the loader will reject the assembly if the assembly's version is lower than the requested version. In your case, assuming that the assembly version matches the package version (which it doesn't have to), your library is requesting version 6.0.0, but the assembly loader/binder, found version 5.2.0 on disk, which is lower. Hence, it rejects that dll, keeps looking, but then can't find a suitable version of the assembly on the probing path and eventually throws the FileLoadException.
What's not clear to me is if this assembly compatibility is checked only on the default assembly loader, or even if you add your own event handler to AssemblyLoadContext.Default.Resolving. You could try adding your own handler and when it requests the assembly of the higher version, you return the lower version assembly anyway. It might be a way to work around the issue.

AddRazorRuntimeCompilation causing deployment problems

When I try to deploy my project it fails with the following message:-
Startup.cs(75,25): error CS1061: 'IMvcBuilder' does not contain a definition for 'AddRazorRuntimeCompilation'
and no accessible extension method 'AddRazorRuntimeCompilation' accepting a first argument of type 'IMvcBuilder'
could be found (are you missing a using directive or an assembly reference?)
I found an answer here How to fix 'IMvcBuilder' doesn't contain a definition for 'AddXmlDataContractSerializerFormatters' however after installing the suggested MVC formatter package(s) The issue persisted.
The only way I have been able to deploy is to comment out the following lines in my startup class
var builder = services.AddRazorPages();
if (Env.IsDevelopment())
{
builder.AddRazorRuntimeCompilation();
}
Maybe I need to update something on the deployment server? It is the organisation's first DotNet Core 3.1 application
You need to install Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation, but not the latest version. Something compatible with .Net Core 3.x.
E.g.
Package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation 3.1.19

Error: Can't load metadata reference from the entry assembly. Make sure PreserveCompilationContext is set to true in *.csproj file

This problem is specific to RazorLight.
Error:
Can't load metadata reference from the entry assembly. Make sure
PreserveCompilationContext is set to true in *.csproj file
This error pops up only after we deploy to AWS. On the local machine things work fine. I've already added PreserveCompilationContext to the *.csproj file.
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
We use circleci for deployments. The API that's having this problem is hosted in AWS Lambda.
private async Task<string> GenerateText(string template, ProseModel model)
{
var engine = new RazorLightEngineBuilder()
.UseMemoryCachingProvider()
.Build();
try
{
// ERROR thrown on next line
var result = await engine.CompileRenderAsync(Guid.NewGuid().ToString(), template, model);
return result;
}
catch(Exception e)
{
Logger.LogError("Error generating template", e);
throw e;
}
}
I found that people are getting this same error in Azure Functions. Is that similar to Lambda's and maybe requires a similar fix? If yes, how can I fix this in a Lambda?
I've also tried to set SetOperatingAssembly(Assembly. GetExecutingAssembly())
I ran into the same issue but the fix that you posted for the Azure Function hack worked for me. You must make sure to replace the "RazorLight" package with the "RazorLight.Unofficial" package version beta1.3. Then it should work.
The problem is that the entry assembly when running on Lambda is called:
Bootstrap, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Which I'm assuming isn't compiled to preserve the compilation context.

Entry point not found in .NET Core 2.0 DLL

I couldn't find anything that explains this -- for some reason my .NET Core 2.0 ASP.NET application does not run as a DLL via:
dotnet MyProject.Web.dll
And instead I get the exception:
Unhandled Exception: System.MissingMethodException: Entry point not found in assembly 'MyProject.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
namespace MyProject.Web
{
public class Program
{
public static void Main(string[] args)
{
LoadDependencies();
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
private static void LoadDependencies()
{
DependencyLocator.Instance.DefineIfUndefined<IDataProvider, DataProvider>();
}
}
}
It runs fine as a standalone executable (when targeting a "Console Application" in the project's config), but now that I'm trying to deploy to a server that needs it to run via the dotnet command (as a DLL, i.e. "dotnet .\MyProject.Web.dll"), it seems to be having issues. I get the above exception on both my server and my local development box.
I'm kind of blown away that it cannot locate the Main method -- it's declared as static and in Program.cs. Am I missing something?
(EDIT: To clarify, the DLL I'm trying to run against the "dotnet" command is from the target compiling as a "Console Library," since my server is explicitly asking for a DLL, since they will not run executables).
OK, so this is annoying and will hopefully help someone else out.
My host wants to specifically run DLL's thru .NET Core ONLY. They do not allow for executables to be run.
Because DLL's are frequently built as "Class Library" output types on the project, I assumed that this was the workflow necessary to build it. However, I found out that whenever you build your project as a "Console Application," it builds a DLL in addition to an EXE. So, in the above example, MyProject.Web.exe and MyProject.Web.dll are both built when the output type is "Console Application."
MyProject.Web.dll that comes from "Console Application" is different than MyProject.Web.Dll that comes from "Class Library." The one that comes from "Class Library" will NOT have an entry point that can be discovered on it, which will lead to the problem above.
So, if you're getting this error, look for the DLL that ships with your EXE of the same name -- that's the actual DLL you'll want to run in your dotnet console (i.e. dotnet MyProject.Web.dll)

'bootstrap' is not a valid script name. The name must end in '.js'

I'm learning asp.net and so I'm trying to build up the project named "Wingtip Toys" from MSDN.
The project is developed on VS 2013 and I have VS 2012. When I try to add Bootstrap per the instruction from here I get the error on runtime in browser.
Server Error in '/' Application.
'bootstrap' is not a valid script name. The name must end in '.js'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: 'bootstrap' is
not a valid script name. The name must end in '.js'.
when I add the .js on the master page it shows me to another error:
The assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not contain a Web resource that has the name 'bootstrap.js'. Make sure that the resource name is spelled correctly.
I also add the CSS file to Bundle.config but still the same result. I already have the NuGet package available, like for the jQuery.js error, but I'm unable to sort this out yet.
Here's what worked for me.
I added this to my BundleConfig.cs file:
ScriptManager.ScriptResourceMapping.AddDefinition("bootstrap", new ScriptResourceDefinition
{
Path = "~/scripts/bootstrap.min.js",
DebugPath = "~/scripts/bootstrap.js",
LoadSuccessExpression = "bootstrap"
});
Please go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solutions.
In Browse, search for: AspNet.ScriptManager.bootstrap
If your version of bootstrap is higher than AspNet.ScriptManager.bootstrap first uninstall bootstrap and then install AspNet.ScriptManager.bootstrap
go to:
Tools
NuGet Package Manager
Manage NuGet Packages for Solutions...
search for Bootstrap.css
install it
try to run your app

Resources