Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor exception wrong line number in form

Why is .NET identifying the incorrect line number when an exception occurs inside form tags? Here is a simple test case in a Razor .cshtml file:

@{
    string[] test = new string[2];
    test[0] = "stuff";
}
@test[0] <br />

<form action="~music/addToCart" method="post">
    <input type="text" name="test" value="@test[2]" />
    <input type="submit" value="Submit" />
</form> 

The exception "Index was outside the bounds of the array" displays the line with test[0] when the actual exception is test[2]. The debugger also shows the incorrect line. It seems that when an exception occurs inside form tags the statement above the form is incorrectly identified as the location of the error. I have tried using the Html helper BeginForm() and got similar behavior.

Using Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2117.0. Visual Studio Community 2017.

like image 793
Apollo Avatar asked Dec 14 '17 19:12

Apollo


1 Answers

I was able to reproduce this. I have a theory:

Consider the original code (with line numbers):

1  - @{
2  -     ViewBag.Title = "Home Page";
3  - }
4  - 
5  - @{
6  -     string[] test = new string[2];
7  -     test[0] = "stuff";
8  - }
9  - @test[0] <br />
10 - 
11 - <form action="~music/addToCart" method="post">
12 -    <input type="text" name="test" value="@test[2]" />
13 -    <input type="submit" value="Submit" />
14 - </form>

The debugger reports line 9 as having the error, but I think that is razor's line number. If we take out any plain text (non-razor):

1  - @{
2  -     ViewBag.Title = "Home Page";
3  - }

4  - @{
5  -     string[] test = new string[2];
6  -     test[0] = "stuff";
7  - }
8  - @test[0] <br />

9  -    <input type="text" name="test" value="@test[2]" />

We see that the error occurs in line 9 within the Razor context.

I think the debugger receives error information with a razor line number and consumes it against the file layout line number.

Definitely a bug. You should report it if someone hasn't already.

like image 150
JuanR Avatar answered Sep 28 '22 23:09

JuanR