Object reference not set to an instance of an object in _Layout.cshtml after updated packages
Asked Answered
N

12

79

The project was running fine until I updated all NuGet packages via NuGet Manager (I was trying to get the latest OWIN packages).

This error is in the _Layout.cshtml and I have not touched it at all.

Object reference not set to an instance of an object.

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.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 13:  
Line 14:     <!-- Custom Fonts -->
Line 15:     @Scripts.Render("~/Content/fonts")

Source File: f:\Workplace\lrc\lrc\Views\Shared_Layout.cshtml Line: 15


Update

Here is the code in the _Layout.cshtml (they are automatically generated when creating the project):

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="LRC - We are aiming at building up a healthier life style.">
    <meta name="author" content="Winston Fan">
    <title>@ViewBag.Title - LRC</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <!-- Custom Fonts -->
    @Scripts.Render("~/Content/fonts")
    
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

So it is complaining this line of code:

@Scripts.Render("~/Content/fonts")

But as you can see that, this is VS generated code, how could I make it wrong?

I also checked the content in the Conntent/font-awesome/fonts folder and all required resources are there.

Here is the code inside the BundleConfig (which is also the auto-generated code):

bundles.Add(new ScriptBundle("~/Content/fonts").Include(
              "~/Content/font-awesome/fonts/fontawesome-*",
              "~/Content/font-awesome/fonts/FontAwesome.otf"));

My Microsoft.OWin.Security, Microsoft.OWin.Security.Google and Microsoft.OWin are version 3.0.1.0.


Update 2

Here is the stack trace:

[NullReferenceException: Object reference not set to an instance of an
object.]    Microsoft.Ajax.Utilities.JSParser.ParseExpression(AstNode
leftHandSide, Boolean single, Boolean bCanAssign, JSToken inToken)
+1007    Microsoft.Ajax.Utilities.JSParser.ParseExpressionStatement(Boolean
fSourceElement) +268   
Microsoft.Ajax.Utilities.JSParser.ParseStatement(Boolean
fSourceElement, Boolean skipImportantComment) +1552   
Microsoft.Ajax.Utilities.JSParser.ParseBlock() +164   
Microsoft.Ajax.Utilities.JSParser.ParseStatement(Boolean
fSourceElement, Boolean skipImportantComment) +498   
Microsoft.Ajax.Utilities.JSParser.ParseBlock() +164   
Microsoft.Ajax.Utilities.JSParser.ParseStatement(Boolean
fSourceElement, Boolean skipImportantComment) +498   
Microsoft.Ajax.Utilities.JSParser.ParseBlock() +164   
Microsoft.Ajax.Utilities.JSParser.ParseStatement(Boolean
fSourceElement, Boolean skipImportantComment) +498   
Microsoft.Ajax.Utilities.JSParser.ParseStatements(Block block) +159   
Microsoft.Ajax.Utilities.JSParser.InternalParse() +1011   
Microsoft.Ajax.Utilities.JSParser.Parse(DocumentContext sourceContext)
+123    Microsoft.Ajax.Utilities.JSParser.Parse(DocumentContext sourceContext, CodeSettings settings) +54   
Microsoft.Ajax.Utilities.Minifier.MinifyJavaScript(String source,
CodeSettings codeSettings) +987   
System.Web.Optimization.JsMinify.Process(BundleContext context,
BundleResponse response) +310   
System.Web.Optimization.Bundle.ApplyTransforms(BundleContext context,
String bundleContent, IEnumerable`1 bundleFiles) +263   
System.Web.Optimization.Bundle.GenerateBundleResponse(BundleContext
context) +355   
System.Web.Optimization.Bundle.GetBundleResponse(BundleContext
context) +104   
System.Web.Optimization.BundleResolver.GetBundleContents(String
virtualPath) +254   
System.Web.Optimization.AssetManager.DeterminePathsToRender(IEnumerable`1
assets) +252   
System.Web.Optimization.AssetManager.RenderExplicit(String tagFormat,
String[] paths) +75   
System.Web.Optimization.Scripts.RenderFormat(String tagFormat,
String[] paths) +292   
System.Web.Optimization.Scripts.Render(String[] paths) +51   
ASP._Page_Views_Shared__Layout_cshtml.Execute() in
f:\Workplace\lrc\lrc\Views\Shared\_Layout.cshtml:15   
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271   
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +121   
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) +145  
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer) +41   
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter
writer) +335    System.Web.WebPages.HelperResult.WriteTo(TextWriter
writer) +42   
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer,
HelperResult content) +45   
System.Web.WebPages.WebPageBase.Write(HelperResult result) +53   
System.Web.WebPages.WebPageBase.RenderSurrounding(String
partialViewName, Action`1 body) +178   
System.Web.WebPages.WebPageBase.PopContext() +229   
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) +154  
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext,
TextWriter writer, Object instance) +695   
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext
viewContext, TextWriter writer) +382   
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+431    System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult) +39   
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1
filters, Int32 filterIndex, ResultExecutingContext preContext,
ControllerContext controllerContext, ActionResult actionResult) +116  
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1
filters, Int32 filterIndex, ResultExecutingContext preContext,
ControllerContext controllerContext, ActionResult actionResult) +529  
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionResult actionResult) +106   
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
+321    System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult
asyncResult) +185   
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult
asyncResult) +42   
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133   
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
Object tag) +56   
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult
asyncResult) +40   
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult
asyncResult, ExecuteCoreState innerState) +34   
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult
asyncResult) +70   
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139   
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
Object tag) +59   
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
Object tag) +40   
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult
asyncResult, Controller controller) +39   
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult
asyncResult) +62   
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139   
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
Object tag) +59   
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
Object tag) +40    System.Web.Mvc.Controller.EndExecute(IAsyncResult
asyncResult) +39   
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult
asyncResult) +39   
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult
asyncResult, ProcessRequestState innerState) +39   
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult
asyncResult) +70   
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139   
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
Object tag) +59   
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,
Object tag) +40   
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+40    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult
result) +38   
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+932    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +188

Update 3

Here is the Content folder:

enter image description here


Update 4

Here is the content of the packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.5.0.2" targetFramework="net451" />
  <package id="bootstrap" version="3.3.4" targetFramework="net451" />
  <package id="EntityFramework" version="6.1.3" targetFramework="net451" />
  <package id="jQuery" version="2.1.3" targetFramework="net451" />
  <package id="jQuery.Validation" version="1.13.1" targetFramework="net451" />
  <package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net451" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.1" targetFramework="net451" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.2.1" targetFramework="net451" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net451" />
  <package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.3" targetFramework="net451" />
  <package id="Microsoft.Owin" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Security" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.Cookies" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.Facebook" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.Google" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.MicrosoftAccount" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.OAuth" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Security.Twitter" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net451" />
  <package id="Modernizr" version="2.8.3" targetFramework="net451" />
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net451" />
  <package id="Owin" version="1.0" targetFramework="net451" />
  <package id="Respond" version="1.4.2" targetFramework="net451" />
  <package id="WebGrease" version="1.6.0" targetFramework="net451" />
</packages>
Naarah answered 13/5, 2015 at 15:53 Comment(10)
Add some more information, from what version to what version did you update. Show your layout file. And put a breakpoint in the file and figure out exactly what is null now.Mele
When you updated did you also update your version of MVC? In any case, what happens when you comment out the offending line?Fieldpiece
hi @Fieldpiece I use Update-Packages -reinstall to update all packages. After I added a try/catch around that line of code, the issue was solved. But that means it will not render the font and that's a big problem. Any advice?Naarah
Layout is template code, not generated code. You are free to modify it. Adding try catch is obviously not your solution. And you still need to share what exactly is null?Mele
Does your NullreferenceException have an inner Exception?Fieldpiece
@YishaiGalatzer yes, it's a template. I cannot tell what exactly is null from the error message I got. So that's why I asked the question here. What else information do I need to provide to figure it out? thank you for your help.Naarah
@Fieldpiece hi, no, there is no inner exception.Naarah
Do you happen to have a folder fonts inside Content?Unabridged
drop a breakpoint on the line where the error is. inspect what is null. If nothing is null there, turn on break on exception thrown and inspect the exception coming back. Another really good alternative is to install the Elmah nuget package. You will get a lot more debugable information.Mele
I was getting a very similar JSParser.ParseExpression exception - it turned out it was the contents of 1 of the .js files being minified! i had mistyped an expression x = ?a.foo?bar:barfoo; deleting the incorrect ? after the equals sign fixed the problem!Coeternal
F
179

Here it was fixed by replacing "ScriptBundle" with "Bundle" in BundleConfig.

We replaced the following:

bundles.Add(new ScriptBundle("~/bundles/mybundle").Include(
            "~/Scripts/...",
            "~/Scripts/..."));

with:

bundles.Add(new Bundle("~/bundles/mybundle").Include(
            "~/Scripts/...",
            "~/Scripts/..."));
Flamingo answered 12/7, 2017 at 11:37 Comment(9)
This worked for me too...looks like an issue in the js file itself can cause it. developercommunity.visualstudio.com/content/problem/86377/…Thorlay
The only difference between a ScriptBundle and a Bundle is that the ScriptBundle uses a “JsMinify” transform (a default one) – this is the same for the StyleBundle vs the Bundle as well (uses a CssMinify). This minification on the script bundle will ALWAYS happen, even in debug mode. blog.travisgosselin.com/net-bundling-minification-top-10-keysDisjunct
For anybody landing here that tries to integrate Angular 8 into an MVC project. THIS is the answer. Guessing angular does some optimizations that cause issues when running through the minifier.Brandon
I just don't understand why this was working fine all the time. And now all the sudden it doesn't work anymore, ScriptBundle has to be changed with Bundle.Underwriter
No clue why this worked but it did. My bundle includes a react / webpack bundle.js.Lollard
does it still minify js files?Deli
I always used ScriptsBundle and it has always worked without a proble,m. Upon using Bootstrap 6 I began receiving the, obkect ref error/ Using Bunde in place of ScriptBundle worked for me solving the object ref error.Scaleboard
For me the bug appeared as soon as I removed the "minify" step from the gulp tasks to be run, which happened before the project build in my case. Changing "ScriptBundle" with "Bundle" did the trick but the fact that this bug still exists is frustrating.Majunga
I got this after updating NuGet packages on a default ASP.Net (non core) MVC site. Probably a version of WebGrease broke it.Lollapalooza
W
36

Check javascript for errors. Mine was a half written line ending with 'function'

Wardieu answered 3/11, 2016 at 9:28 Comment(3)
In my case I had accidentally named one of my variables "new"Mcglothlin
Somehow managed to get function*(){...} in my code, no lint error either with itGong
We had some git merge artifacts that polluted a JS file which broke the bundler. Removing the artifacts which broke the JS file fixed the bundling.Clamworm
M
9

This looks like a bug in the javascript minifier.

Microsoft.Ajax.Utilities.Minifier.MinifyJavaScript(String source, CodeSettings codeSettings) +987

Please file a connect bug (i'll forward this thread internally in Microsoft as well).

As a workaround you can minify the scripts manually and include them directly instead of using the bundler.

Can you share your packages.config please? It will help with tracking this potential bug.

Mele answered 14/5, 2015 at 2:59 Comment(4)
Hi Yishai, thank you very much for identify this issue. Could you please include the url to file a connect bug? ThanksNaarah
Hi Yishai, please take look the Update 4 which has the content of the packages.configNaarah
I'm walking on a limb here, but you can try downgrading Microsoft.AspNet.Web.Optimization and WebGrease one version at a time. If you find which one makes it work again please let us knowMele
I still have the minimizer fail whenever using optional chaining, ie, o?.x.Piffle
E
6

So I ran into this bug earlier today and was able to track down the offending code. For myself, the minifier was choking on a bad line of javascript that was incorrectly using a ternary statement of the form:

var test = condition ? true_value ? false_value;

Obviously, the second question mark should have been a colon to make a valid ternary statement. This caused the entire application to crash throwing the same error above. Perhaps this isn't the same issue you ran into, but it gives the same results.

Etherege answered 12/8, 2015 at 19:46 Comment(0)
C
4

I have read that changing the way bundles are created in BundleConfig.cs could solve the issue. So I tried to replace :

bundles.Add(new ScriptBundle(“~/bundles/bootstrap”).Include(“~/Scripts/bootstrap.js”));

by

bundles.Add(new Bundle(“~/bundles/bootstrap”).Include(“~/Scripts/bootstrap.js”));

With this change, project runs without exception, webpage is displayed, but it looks rendered without css. Display does not look as it should.

Cloudcapped answered 7/11, 2022 at 17:35 Comment(0)
C
2

In my case, it's due to changes in verdor libs so I can't fix the js file directly.

My work around is to use the min version which is indicate to the bundle: DO not minify this file.

For example: Simply move from select2.js to select2.min.js

Crossjack answered 5/12, 2017 at 10:50 Comment(2)
I'm on net core, this is the only one that helped me. I also had to disable minification in my bundle config, besides renaming the files: "outputFileName": ..., "inputFiles": [ ... ], "minify": { "enabled": false }Binomial
what that makes no sense but works @MiguelHughes thxGaunt
R
2

Make sure you replace all ScriptBundle with Bundle in BundleConfig

Rozier answered 26/9, 2023 at 18:17 Comment(0)
U
1

ScriptBundleclass can be used for bundling scripts and cannot be used for bundling styles. It is coupled with @Scripts.Render("~/scripts/bundle") that renders a <script> tag.

For styles there is StyleBundle class

bundles.Add(new StyleBundle("~/bundles/mybundle").Include(
        "~/Content/...",
        "~/Content/..."));

and it is coupled with @Styles.Render("~/content/bundle") that creates a <link> tag.

Ukulele answered 4/8, 2017 at 9:8 Comment(0)
Z
1

There must be a javascript error.

Undo your changes and just check your changes by putting one by one and check the browser with those changes as well.

Zilla answered 16/3, 2020 at 11:49 Comment(2)
what if i made changes bootstrap does not work anymore i take back the changes and still does not work?Snoopy
@KristófHorváth javascript is one of the hardest languages to find the issue and resolve. So need to check thoroughly and still the same issue appears then just need to check other files or associated files also.Zilla
H
1

In my case the bundler/minifier did not seem to like template literals ending with a newline.

This works (no leading/trailing newlines):

    var t = `<div>
    ...
</div>`;

This works (leading newline):

    var t = `
<div>
    ...
</div>`;

This works (leading/trailing newlines indented with whitespace):

    var t = `
        <div>
            ...
        </div>
        `; // closing backtick with some whitespace in front

As soon as I do this the @Scripts.Render bombs out:

    var t = `
<div>
    ...
</div>
`; // closing backtick at the start of the line
Hounding answered 3/11, 2022 at 13:24 Comment(0)
F
1

I'm experiencing the same problem now. and I've just found out experimentally that it stumbles over EcmaScript 6 features (for instance, "let" keyword). I think this is the reason the problem has appeared after nuget update in your case. in my case "new ScriptBundle -> new Bundle" also helped, thanks!

Fibroblast answered 23/1, 2024 at 13:50 Comment(0)
S
0

Maybe I can be usefull for someone at 2024. I faced with that issue using .NET Framework 4.8 MVC. In .js files I can write new modern syntax, inculding ..., object?. etc. And this 'new' syntax bring an error, ScriptBundle library doesn't want to eat it :(

To solve that I used Transforms.Clear() (something not good, but anyway):

            bundles.Add(viewBundle);
            bundles.Add(viewComplexBundle);
#if DEBUG
            viewBundle.Transforms.Clear();
            otherBundles.Transforms.Clear();
            sharedBundle.Transforms.Clear();
#endif
            viewComplexBundle.Transforms.Clear();
Salmonella answered 14/5, 2024 at 16:36 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.