Skip to content
This repository has been archived by the owner on Dec 19, 2018. It is now read-only.

TestServer - Crash when calling a razor view #954

Closed
Axel3232 opened this issue Mar 2, 2017 · 17 comments
Closed

TestServer - Crash when calling a razor view #954

Axel3232 opened this issue Mar 2, 2017 · 17 comments

Comments

@Axel3232
Copy link

Axel3232 commented Mar 2, 2017

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 
@Tratcher
Copy link
Member

Tratcher commented Mar 2, 2017

@NTaylorMullen?

@JvanderStad
Copy link

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 ™️

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);

@Axel3232
Copy link
Author

@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.

@JvanderStad
Copy link

Sure np.

But I think it's a bug 🐛,
we should not include references from the main project manually, this should be done automatically.

@rodchenkov
Copy link

I have the same issue!
Please, can someone explain why it was closed?

@Axel3232
Copy link
Author

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

@Axel3232 Axel3232 reopened this Mar 17, 2017
@muratg
Copy link

muratg commented Mar 20, 2017

@Eilon can @NTaylorMullen or someone from Razor look into this?

@NTaylorMullen
Copy link
Contributor

You need to copy your applications deps.json file into your test application. See what we do here in MVC to make this work.

@Eilon
Copy link
Member

Eilon commented Mar 21, 2017

I think this is a dup of aspnet/Mvc#3410.

@Eilon Eilon closed this as completed Mar 21, 2017
@amattie
Copy link

amattie commented Mar 23, 2017

@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.

@amattie
Copy link

amattie commented Mar 23, 2017

Check that. Turns out it's microsoft/vstest#428 that's the core issue. #959 (comment) worked for me as a workaround in case anyone else stumbles here.

@Eilon
Copy link
Member

Eilon commented Mar 23, 2017

@amattie ah ok thank you!

@kdowswell
Copy link

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 #959 (comment)

The failing test project is .net461 calling a asp.net core 461 site

@ales004
Copy link

ales004 commented Jul 10, 2017

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.

@JoseFMP
Copy link

JoseFMP commented Aug 10, 2017

Dudes this is terrible... and closed as duplicated but no pointer to the duplicated issue so that we can track it?!

@davidfowl
Copy link
Member

It's right here aspnet/Mvc#3410 (comment)

@davidikin45
Copy link

davidikin45 commented May 15, 2018

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);

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests