TestServer - Crash when calling a razor view
HI
I am using thedefault AspNetCore WebApplication (netcoreapp1.1) template (no modification) and a default .NET Core Unit test project Every package have been updated to 1.1
The unit test is as simple as :
[TestMethod]
public async Task TestMethod1()
{
var applicationBasePath = @"the path to WebApplication3"
var builder = new WebHostBuilder()
.UseEnvironment("Developpement")
.UseKestrel()
.UseContentRoot(applicationBasePath)
.UseStartup<WebApplication3.Startup>();
var server = new TestServer(builder)
{
BaseAddress = new Uri("http://localhost:1987"),
};
var client = server.CreateClient();
var res = await client.GetAsync("/Home/About");
}
When trying to call an the "/Home/About" (or any other action that render a view) I can stepin in the action code, but as soon as the action return anc ompile the view I get this error : Note that the site is working if I start it normally.
> Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware:Error: An unhandled exception has occurred: One or more compilation failures occurred:
krhie2b1.cjs(10,11): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
krhie2b1.cjs(11,11): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
krhie2b1.cjs(12,11): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
krhie2b1.cjs(15,36): error CS0234: The type or namespace name 'ViewFeatures' does not exist in the namespace 'Microsoft.AspNetCore.Mvc' (are you missing an assembly reference?)
krhie2b1.cjs(16,11): error CS0246: The type or namespace name 'System' could not be found (are you missing a using directive or an assembly reference?)
krhie2b1.cjs(18,86): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference?
krhie2b1.cjs(18,86): error CS0518: Predefined type 'System.Boolean' is not defined or imported
krhie2b1.cjs(18,45): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
krhie2b1.cjs(26,16): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
krhie2b1.cjs(26,16): error CS0518: Predefined type 'System.Object' is not defined or imported
krhie2b1.cjs(26,41): error CS0234: The type or namespace name 'ViewFeatures' does not exist in the namespace 'Microsoft.AspNetCore.Mvc' (are you missing an assembly reference?)
krhie2b1.cjs(26,110): error CS0518: Predefined type 'System.Void' is not defined or imported
krhie2b1.cjs(28,16): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
krhie2b1.cjs(28,16): error CS0518: Predefined type 'System.Object' is not defined or imported
krhie2b1.cjs(28,41): error CS0234: The type or namespace name 'IUrlHelper' does not exist in the namespace 'Microsoft.AspNetCore.Mvc' (are you missing an assembly reference?)
krhie2b1.cjs(28,63): error CS0518: Predefined type 'System.Void' is not defined or imported
krhie2b1.cjs(30,16): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
krhie2b1.cjs(30,16): error CS0518: Predefined type 'System.Object' is not defined or imported
krhie2b1.cjs(30,41): error CS0234: The type or namespace name 'IViewComponentHelper' does not exist in the namespace 'Microsoft.AspNetCore.Mvc' (are you missing an assembly reference?)
krhie2b1.cjs(30,79): error CS0518: Predefined type 'System.Void' is not defined or imported
krhie2b1.cjs(32,16): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
krhie2b1.cjs(32,16): error CS0518: Predefined type 'System.Object' is not defined or imported
krhie2b1.cjs(32,51): error CS0234: The type or namespace name 'IJsonHelper' does not exist in the namespace 'Microsoft.AspNetCore.Mvc.Rendering' (are you missing an assembly reference?)
......
krhie2b1.cjs(39,36): error CS0161: '_Views_Home_About_cshtml.ExecuteAsync()': not all code paths return a value
/Views/Home/About.cshtml(2,5): error CS0012: The type 'ViewDataDictionary<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.AspNetCore.Mvc.ViewFeatures, Version=1.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
/Views/Home/About.cshtml(2,14): error CS0518: Predefined type 'System.String' is not defined or imported
/Views/Home/About.cshtml(2,25): error CS0518: Predefined type 'System.String' is not defined or imported
/Views/Home/About.cshtml(4,7): error CS0012: The type 'ViewDataDictionary<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.AspNetCore.Mvc.ViewFeatures, Version=1.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
/Views/Home/About.cshtml(4,16): error CS0518: Predefined type 'System.String' is not defined or imported
/Views/Home/About.cshtml(4,1): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
/Views/Home/About.cshtml(4,1): error CS0518: Predefined type 'System.Object' is not defined or imported
/Views/Home/About.cshtml(4,1): error CS0518: Predefined type 'System.Void' is not defined or imported
/Views/Home/About.cshtml(5,7): error CS0012: The type 'ViewDataDictionary<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.AspNetCore.Mvc.ViewFeatures, Version=1.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
/Views/Home/About.cshtml(5,16): error CS0518: Predefined type 'System.String' is not defined or imported
/Views/Home/About.cshtml(5,1): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
/Views/Home/About.cshtml(5,1): error CS0518: Predefined type 'System.Object' is not defined or imported
/Views/Home/About.cshtml(5,1): error CS0518: Predefined type 'System.Void' is not defined or imported
at Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationResult.EnsureSuccessful()
at Microsoft.AspNetCore.Mvc.Razor.Internal.CompilerCache.CreateCacheEntry(String relativePath, String normalizedPath, Func`2 compile)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Razor.Internal.CompilerCache.GetOrAdd(String relativePath, Func`2 compile)
at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(String relativePath)
at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet`1 expirationTokens, String relativePath, Boolean isMainPage)
at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, String pageName, Boolean isMainPage)
at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
at Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.FindView(ActionContext actionContext, ViewResult viewResult)
at Microsoft.AspNetCore.Mvc.ViewResult.<ExecuteResultAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeResultAsync>d__30.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResultFilterAsync>d__28.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResultExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method WebApplication3.Controllers.HomeController.Error (WebApplication3) with arguments ((null)) - ModelState is Valid
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action WebApplication3.Controllers.HomeController.Error (WebApplication3) in 72.2828ms
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware:Error: An exception was thrown attempting to execute the error handler.
System.ArgumentException: An item with the same key has already been added. Key: System.Object
at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
Exception levée : 'Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException' dans System.Private.CoreLib.ni.dll
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 1948.2299ms 500
@NTaylorMullen?
Had the same issue.. After some digging found a working solution..
The roslyn compiler used in Razor doesn't include the referenced assemblies of the main assembly.. So I added these by looking them up
In the test class add the following code.. Works on my machine :tm:
private static string ContentPath
{
get
{
var path = PlatformServices.Default.Application.ApplicationBasePath;
var contentPath = Path.GetFullPath(Path.Combine(path, $@"..\..\..\..\{nameof(src)}"));
return contentPath;
}
}
var builder = new WebHostBuilder()
.UseContentRoot(ContentPath)
.ConfigureLogging(factory =>
{
factory.AddConsole();
})
.UseStartup<Startup>()
.ConfigureServices(services =>
{
services.Configure((RazorViewEngineOptions options) =>
{
var previous = options.CompilationCallback;
options.CompilationCallback = (context) =>
{
previous?.Invoke(context);
var assembly = typeof(Startup).GetTypeInfo().Assembly;
var assemblies = assembly.GetReferencedAssemblies().Select(x => MetadataReference.CreateFromFile(Assembly.Load(x).Location))
.ToList();
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Private.Corelib")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor")).Location));
context.Compilation = context.Compilation.AddReferences(assemblies);
};
});
});
_server = new TestServer(builder);
@JvanderStad thank a lot, it worked but I had to add these assemblies :
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Private.Corelib")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Linq")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Threading.Tasks")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Runtime")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Dynamic.Runtime")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor.Runtime")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Mvc")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Mvc.Razor")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Html.Abstractions")).Location));
assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Text.Encodings.Web")).Location));
But I am wondering why this not already configured in the testserver plumbing.
Sure np.
But I think it's a bug :bug:, we should not include references from the main project manually, this should be done automatically.
I have the same issue! Please, can someone explain why it was closed?
I closed it too quickly because I was able to move on with the workaround. But you are right, it feels like this should be fixed, all those plumbing code should be automatically wired into the testserver
@Eilon can @NTaylorMullen or someone from Razor look into this?
You need to copy your applications deps.json file into your test application. See what we do here in MVC to make this work.
I think this is a dup of https://github.com/aspnet/Mvc/issues/3410.
@Eilon I'm not so sure this is a dupe. I'm using the right ContentPath, but my tests still fail according to the original description. When I purposefully break my ContentPath, I get a distinctly different error indicating an InvalidOperationException with a message indicating my view can't be found in the content-path-relative locations.
Check that. Turns out it's Microsoft/vstest#428 that's the core issue. https://github.com/aspnet/Hosting/issues/959#issuecomment-286351703 worked for me as a workaround in case anyone else stumbles here.
@amattie ah ok thank you!
The above workaround is working for me except for pages that use @ViewBag. The exception I get is "Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'" I tried to add "assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.CSharp")).Location));" to the list of RazorViewEngineOptions but that throws an error not finding the assembly. I also have the fixes in my .csproj from https://github.com/aspnet/Hosting/issues/959#issuecomment-286351703
The failing test project is .net461 calling a asp.net core 461 site
Are there some plan to repair this problem? I just had the same problem and it took me a while to understand where this was coming from. The only thing that worked for me was what explained in the comment above.
Dudes this is terrible... and closed as duplicated but no pointer to the duplicated issue so that we can track it?!
It's right here https://github.com/aspnet/Mvc/issues/3410#issuecomment-315425178
For anyone targeting .Net Framework 4.7.1 or 4.7.2 this worked for me
previous?.Invoke(context);
var assembly = typeof(Startup).GetTypeInfo().Assembly; var assemblies = assembly.GetReferencedAssemblies().Select(x => MetadataReference.CreateFromFile(Assembly.Load(x).Location)) .ToList();
string netVersion = "v4.7.2"; assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Html.Abstractions")).Location)); assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Http.Features")).Location)); assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.Extensions.Primitives")).Location)); assemblies.Add(MetadataReference.CreateFromFile(Assembly.LoadFrom(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework"+ netVersion + @"\Facades\netstandard.dll").Location));
context.Compilation = context.Compilation.AddReferences(assemblies);