Razorlight: .NET Core v2.1 SDK broke RazorLight in console app

Created on 25 May 2018  Â·  44Comments  Â·  Source: toddams/RazorLight

I was using RazorLight fine in VS2017 with .NET Core 2.0. I've tested to upgrade to .NET Core 2.1 SDK (so it's building using .NET Core 2.1 RC1, but also tested with the release of 2.1, same issue) and that broke my console app when calling CompileRenderAsync. It still works if I call this from a ASP.NET Core project type (which is targeting .NET Core 2.0). I have PreserveCompilationContext in the csproj set to true, but still getting this:

Failed to compile generated Razor template:
- (3:35) The type 'Attribute' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
- (3:63) Predefined type 'System.String' is not defined or imported
- (3:76) Predefined type 'System.Type' is not defined or imported
- (3:10) Predefined type 'System.Void' is not defined or imported
- (11:37) The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.

_(and 100s more of these)_

I saw this issue, but I'm not 100% sure it's related: https://github.com/dotnet/sdk/issues/2092. To me it seems something in the build process has changed, but I don't know if it's a known issue or if there is a fix.

Most helpful comment

Many thanks.

I think that this line in .csproj solved the issue.

<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>

All 44 comments

we are having exactly the same error from our xunit tests

RazorLight is not tested on .NET Core 2.1, as it has just released recently

I will save this issue to avoid duplicates

FYI, it happens both in the RC1 (maybe previews as well) and in the 2.1 release.

FYI- I created an empty Net Core 2.1 App making few simple calls to RazorLight 2.0.0-beta1 and it is working fine.

We have seen similar issue with .Net Core 2.0 app though with SDK 2.1.300. The issue occurs after we removed the AssetTargetFallback attribute from the csproj.

Adding it back with $(AssetTargetFallback) value solved our problem.

I don't have the fallback attribute in my project files (also compiling works fine so doesn't seem to be related). I get a runtime error when calling CompileRenderAsync from a string (which is a cshtml file). It works when I built this using .NET Core SDK 2.0, but with the 2.1 SDK it doesn't work any more, doesn't matter if I set the target to 2.0 or 2.1, it seems that the 2.1 build system does things differently that isn't working with RazorLight.

Is there a reliable work-around for this?

@HakanL This is odd. I checked again and it is working on my end using SDK v2.1.300.
dotnet output

Happy to share the project code or try running a test project too

@superjulius I'm running my RazorLight in a separate class library. I'll do some tests to see if that's the determining factor for this bug.

~Ok. Well, 2.1.300 seems to work fine!~ It only works on Windows. Linux/Docker does not work.

Hmm, of course it works when I create a new solution (with RazorLight in a referenced project). I've compared the csproj files and they seem to match. (I'm on Windows). I guess I need to tinker around with it some more to figure out what's different. BTW, what does the error messages mean, that it can't find System assemblies or something?

I don't have the exact stack trace, but I'm guessing it has something to do with the compilation step: https://github.com/toddams/RazorLight/blob/master/src/RazorLight/Compilation/RoslynCompilationService.cs#L172. I assume that the DLLs that it needs are just missing at runtime!?

@HakanL FWIW: I was able to resolve the issue by deploying a framework-dependent binary, (not using -r linux). Hope this helps.

I get the error even in debug (Visual Studio 2017) in Windows. But it's interesting that it works in a new console project, I need to break apart my larger app and see where it's failing.

I'm struggling with this same issue...was there any resolution?

+1. Seeing this with the FluentEmail package which depends on RazorLight.

I'm struggling with this same issue...was there any resolution?

I figured out the issue in my case at least, which may also explain why creating a new project @HakanL worked for you.
In my case I was still using version 1.1 because that made it easy to compile from dynamic string templates (versus embedded or files). I had to refactor somewhat and create my own template provider to upgrade to 2.0.0-beta1, but doing so resolved my issue.
Is it possible that others here are using a previous version (even one of the 2.0.0-alpha) versions? @IndexOverflow : If you are using FluentEmail, this also only requires one of the 2.0.0-alpha versions, and nuget by default will just use what you have cached locally if it satisfies the requirement.
So I would put an explicit reference to RazorLight 2.0.0-* in your project and make sure to do a dotnet restore --no-cache from the command line to make sure your lock file/cache gets updated to the latest version.

Thanks for the tip, but my project is a new 2.1 project just recently created. No legacy / upgrade issues to look into.

Installing Microsoft.CSharp version 4.5.0 solved the issue for me

I just figured out what caused the issue for me. In my bin\debug folder there was an empty directory called "refs" which caused this issue. If I deleted this (empty) folder then everything worked! Not sure what created this, it wasn't re-created if I did rebuild all, but this project was taken from .NET Core 1 up to 2.1 over the last 9 months, so maybe something happened there.

Hi, I have a WebAPI AspNetCore 2.1x project with embedded cshtml and I am using RazorLight with Docker/Linux. When I run locally on my machine via Docker all works well; when I push to AWS same it gives me an ERROR with no output, just a blank exception - any thoughts appreciated?

Hi,

I run into same problem. When i use it locally on my machine everything works fine. But when I deploy it to MS Azure I get an error "You must add a reference to assembly 'System.Private.CoreLib'"

Im using .NET 2.1,

When i used this library with .NET 2.0. I must chose deploy self-contained which solved the problem. But with .NET 2.1 it didn't help.

Any suggestion?

Have you added UseStaticFiles in the startup as that seemed to resolve it for me I shall send the other config changes when I get back to my computer


From: Jan Branný notifications@github.com
Sent: Tuesday, August 14, 2018 5:31 pm
To: toddams/RazorLight
Cc: Ribeye Kind; Comment
Subject: Re: [toddams/RazorLight] .NET Core v2.1 SDK broke RazorLight in console app (#188)

Hi,

I run into same problem. When i use it locally on my machine everything works fine. But when I deploy it to MS Azure I get an error "You must add a reference to assembly 'System.Private.CoreLib'"

Im using .NET 2.1,

When i used this library with .NET 2.0. I must chose deploy self-contained which solved the problem. But with .NET 2.1 it didn't help.

Any suggestion?

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHubhttps://github.com/toddams/RazorLight/issues/188#issuecomment-412934091, or mute the threadhttps://github.com/notifications/unsubscribe-auth/AJweYPAr6z1qCgYMcIwfPC-ew-r4JbQnks5uQvtBgaJpZM4UNGiy.

In the csproj I added (as per instructions)

<PreserveCompilationContext>true</PreserveCompilationContext>
<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>

In the Program.cs

.UseContentRoot(Directory.GetCurrentDirectory())

and in Startup.cs

app.UseDefaultFiles();
app.UseStaticFiles();

TBH I do not which (or combination of) changes resolved my issue only that they did. I will be doing to RCA this weekend to understand more; but my project deadlines did not afford me the opportunity to investigate at the time.

Hope this helps; if not get back in touch and I will see how I can assist further.

Many thanks.

I think that this line in .csproj solved the issue.

<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>

<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish> solved the issue for me.

Confirm that the solution from @Brandejs and @gitsnail worked. Thanks also @MIKE-R-PALMER
Please @toddams add this setting in the readme file as it is a common issue :) Thanks

Great thanks guys, I never did get to opportunity to do the root cause but now I know I shall clean up my code. Appreciate the update.

Great thanks guys, I never did get to opportunity to do the root cause but now I know I shall clean up my code. Appreciate the update.

If I use the the Razor Light in a Console Application, I still need to add <PreserveCompilationContext>true</PreserveCompilationContext> so I think you don`t need to cleanup. I added also just to be sure.

Brilliant, thanks again

So there is MvcRazorExcludeRefAssembliesFromPublish, MvcRazorCompileOnPublish, PreserveCompilationContext, RazorCompileOnPublish and RazorCompileOnBuild. Only 32 combinations to try for the one which might work -- if there is any at all.

Is anyone able to explain what each of these settings is really doing, let alone the combinations of these?

Any news on this? I have tried all the above with no luck. @toddams
Thanks you

L.E. I published without -r win-x64 and works fine...meh

This fixed it for me!

<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>

This fixed it for me!

<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>

Where exactly in the .csproj did you set this?

Edit: Figured it out. Put it on my first PropertyGroup

Hello everyone, I'm publishing a Net Core WebApp (version 2.2.108) on host SmaterAsp.net in self-contained deployment mode.

My CSPROJ file looks like this:

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    <UserSecretsId>438bea06-a241-4638-a75d-2c9de371a6b3</UserSecretsId>
    <AssemblyName>ProjectName.UI.Web.Admin</AssemblyName>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
  </PropertyGroup>

After publishing and running WebApp I saw that the links weren't working and the generated HTML code was the same as Razor, like this:

<a asp-area="" asp-controller="Ticket" asp-action="Index">Tickets</a>

But the correct one should be:

<a href="/Ticket/Index">Tickets</a>

If I publish without the parameters below:

<PreserveCompilationContext>true</PreserveCompilationContext>
<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>

I have the following error:

Error - The type 'Attribute' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=

Can you tell me what I did wrong or how to adjust it?

Thanks in advance for your time.

In my case, setting MvcRazorExcludeRefAssembliesFromPublish did not change anything (PreserveCompilationContext was already in place).

But https://stackoverflow.com/a/39049422 helped. Specifically:

```c#
var builder = new RazorLightEngineBuilder()
.UseFilesystemProject(ResourceFileUtil.GetCopyToOutputDirectoryLocation(GetType(), RazorTemplatesDirectory))
.UseMemoryCachingProvider();

// workaround to be able to compile Razor templates in self-contained deployments
var coreDir = Directory.GetParent(typeof(Enumerable).GetTypeInfo().Assembly.Location);
var myDir = Directory.GetParent(GetType().GetTypeInfo().Assembly.Location);

if (coreDir.FullName == myDir.FullName)
{
builder.AddMetadataReferences(
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location));
}
```

Updated FAQ with guidance.

I think in .Net Core 3, you should use
<PreserveCompilationContext>true</PreserveCompilationContext>
<PreserveCompilationReferences>true</PreserveCompilationReferences>

@rdhainaut That's what our FAQ says: https://github.com/toddams/RazorLight/#im-getting-cannot-find-reference-assembly-microsoftaspnetcoreantiforgerydll-exception-on-net-core-app-30-or-higher

Can you please explain if the FAQ is not clear. Feedback is very helpful.

@jzabroski Thank for the link. The FAQ is very clear about this but when you search the solution at this problem via search engine you get this thread and not the FAQ ...
So i have added the answer here for the .net Core 3 (but a link to FAQ is a good answer too !).

In my case (I have .net core 3.1 app for win10-x64 which I build on Linux machine) I had to remove -p:PublishTrimmed=true from the dotnet publish command :(

@nZeus I believe you can set <PublishTrimmed>True</PublishTrimmed> in your endpoint csproj file, so as to avoid specifying it on the command line every time.

Can I ask how you discovered this knob even exists, and what led you to find out this works?

My console app generates an html report with the help of RazorLight.
I get a lot of similar errors from RazorSharp when using the PublishTrimmed option:

Failed to compile generated Razor template:
 (3:35) The type 'Attribute' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
...

I've also tried <TrimmerRootAssembly Include="System.Private.CoreLib" /> - but that doesn't help for some reason :(


I prefer to keep -p:PublishTrimmed next to the dotnet publish command, as it makes no sense to have it in the csproj file. This is the setting related to the distribution of an app. Keeping it close to the publish script makes it better organized

Interesting. I had no idea these helpers existed. Learn something new every day! Thanks for sharing! Glad I asked you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

IInvocation picture IInvocation  Â·  6Comments

AdrianPell picture AdrianPell  Â·  4Comments

dombarnes picture dombarnes  Â·  7Comments

WaltDaniels picture WaltDaniels  Â·  6Comments

shobman picture shobman  Â·  4Comments