I have a .NET Framework 4.7.2 web application. I am receiving the following yellow screen error from some of my Views and Partial Views but not all of them:
Expected a "{" but found a "using".
Block statements must be enclosed in "{" and "}".
You cannot use single-statement control-flow statements in CSHTML pages...
Some of the Views and Partial Views within the web application work with streams which need to be disposed. I realize that razor is not the ideal place to work with streams. For now, I am seeking to understand why Razor likes my using statements sometimes but not others.
One of the Views has code like this which works great:
@{
string baseUrl = "redacted";
string requestUrl = "redacted";
...
...
#region Redacted Region Name
try
{
HttpWebRequest httpWebRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
httpWebRequest.Method = "GET";
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var data = reader.ReadToEnd();
...
}
}
catch (Exception ex)
{
...
}
#endregion
}
However, a separate view with the following using statement would result in the yellow screen error and Visual Studio complaining about syntax errors:
@{
string baseUrl = "redacted";
string requestUrl = "redacted";
...
...
HttpWebRequest httpWebRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
httpWebRequest.Method = "GET";
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var data = reader.ReadToEnd();
...
}
}
I know I can just apply explicit curly brackets and my problem will be solved as in the below snippet of code. I'd like to understand why I can't stack the using statements and omit some of the curly brackets in some of my Views. Why does it work sometimes but not others in Razor?:
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var data = reader.ReadToEnd();
...
}
}
}
The problem appears to be with how Razor decides if I am using a "using statement" or a "using directive" (see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using)
So far, I have found three ways to communicate to Razor that I want to use the
usingkeyword for a "using statement"usingstatements in a#regionI am surprised by the
#regionsolution, but it does seem to work, but you have to be careful not to do anything between the opening of the#regionand the scope that contains the usage of the "using statement"This is ok:
This has syntax errors where Razor believes the
usingkeyword is for a "using directive"