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(); ... } } }