A Interesting Observation
In Asp.Net Core the HttpContext.Response.HasStarted
property indicates whether the response has startedor not. Once it has started, you can not change the response since some of the bytes have already been sent to the browser.
I have observed what looks like strange behavior to me, where the inclusion of UseBrowserLink()
in the Startup.cs Configure
method causes the response to start later than it otherwise would.
Since it's common to use BrowserLink in dev but not in production, this means that the timing of HttpContext.Response.HasStarted
is different for dev vs production, which is not ideal.
Example:
I just used the basic MVC template, to start with, I tried both the one for Asp.Net Core 2.2 and 3.1 and they both exhibit this behavior. I will show the code below for 3.1 since it's the newer of the two.
Index.cshtml
@{
Layout = "";
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Pretty Basic Page</h1>
</body>
</html>
HomeController.cs Action Method
public IActionResult Index() {
return View();
}
Startup.cs Configure method
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseStaticFiles();
//app.UseBrowserLink();//run code, then uncomment and run again
app.Use(async (context, next) => {
await next();
string path = context.Request.Path.ToString();
bool hasStarted = context.Response.HasStarted;
int i = 1; //SET BREAK POINT HERE
});
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
If you set a breakpoint at the spot indicated and run this code, hasStarted
will be true
. Then if you uncomment the app.UseBrowserLink()
line, and run the code again stopping at the breakpoint you will see that hasStarted
is now false
.
What's up with that? This means that if I was using browserlink in dev, I could think that I'm allowed to modify the response at this point, but then when the code runs in production without app.UseBrowserLink()
any code that attempts to modify the response at this point will be unsuccessful.
Why does BrowserLink cause this behavior? Actually I like that rendering starts later but I want the start point to be the same with or without BrowserLink. How can I get the code to start rendering later even when UserBrowserLink
is not called?