1

I have in a Razor view file:

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<pre>@Model.Exception.Message</pre>
<pre>@Model.Exception.InnerException?.Message</pre>
<pre>@Model.info</pre>

The InnerException?.Message shows more than the Message property. It looks like the output of the ToString() method:

enter image description here

If I instead of the null conditional operator I used:

@if (Model.Exception.InnerException != null)
{
  <pre>@Model.Exception.InnerException.Message</pre>
}

then it comes out as I wanted:

enter image description here

Is the syntax I am using for the null conditional operator incorrect?

Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • `@(Model.Exception.InnerException?.Message)` does this work ? – TheGeneral Jan 28 '19 at 05:25
  • (Y)! Thanks. There was no error without the parentheses so how was the `?` interpreted? – Old Geezer Jan 28 '19 at 05:28
  • Im guessing it just allows it to parse better, i dont really have an explanation, maybe someone can answer with one – TheGeneral Jan 28 '19 at 05:30
  • Interesting, I would expect the string "?.Message" at the end of the stack trace in your first example, which is hidden in the screenshot. – yv989c Jan 28 '19 at 06:15
  • Yes, it was "...Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)?.Message". So it looks like it treated `?.Message` as literal text. – Old Geezer Jan 28 '19 at 06:20

1 Answers1

1

I think the problem occurred because implicit Razor expression is used with HTML tag precedes it:

<pre>@Model.Exception.InnerException?.Message</pre>

which interpreted as this, hence the parser only reads Model.Exception.InnerException property:

<pre>@(Model.Exception.InnerException.ToString())?.Message</pre>

The null-conditional operator in C# 6.0 and above requires usage of explicit expression in certain Razor versions before introduction of C# 6.0 because the implicit expression parser still following previous versions of C# syntax. Since the explicit expression syntax allows flexibility to parse server-side code according to current C# version, the expression above should be written like this:

<pre>@(Model.Exception.InnerException?.Message)</pre>

Note:

This is an edge case which Razor misinterpreted null-conditional operator as part of literal string instead of code with implicit expression, and explicit expression helps render property content.

Reference:

Explicit Razor expressions

Related issue:

The new null-conditional operator in ASP.NET MVC Razor

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61