I’m on a ASP.NET Core Web App (Model-View-Controller) on .NET 6.0 and I’m trying to show a determinate view when some internal asynchronous task wants.
Here’s what I’ve tried:
Task.RunAsync(() =>
{
Thread.Sleep(10000);
HttpContext.Current.Response.Redirect("/Index");
});
What it happens is that I get System.ObjectDisposedException: IFeatureCollection has been disposed.
.
I’ve tried some other things like using IServiceScopeFactory but I dont’t completely know how to use it correctly.
I’d really appreiate some help on this.
2
Answers
You can’t redirect your user after a page is loaded by using
HttpContext.Current.Response
as this uses HTTP redirect codes (which you can read here). If your user see’s a page (which I assume after 10 seconds is the case) you already have returned a200
code. And after that you can’t return a other one, as the request is already fulfilled. You can read here how HTTP redirection works if you want to.If you want to implement redirection after a page load, you will need to implement some JavaScript which does the redirection for you. This can be achieved for example by doing:
But you will want to call this JS only after something in your backend is completed so you may want to add an API endpoint which you can call and returns after your operation is completed:
or if you exactly know the delay you don’t need JS you can simply use an meta refresh tag in your header:
You should avoid accessing
HttpContext
directly within theTask.RunAsync
method. You can useIServiceScopeFactory
.Example:
In your action method: