We have a well established ASP.NET webforms site (not project, not MVC, not .NET Core) based on the .NET Framework 4.8. We would like to start integrating some REST based services which quickly gets into HttpClient
and async
based methods.
I have a test page that appears to "work" but I am concerned the pattern is not set up right based on a "thread abort error" that is being caught.
The idea is, there is a webforms page that has a button on it; the user clicks the button, the code-behind for that button ends up making a REST call to an endpoint to get back some data. That all works.
But, we'd like to shuffle the user to another page at the end of that, so a "redirect" is called. And that ends up causing the "Thread was being aborted" exception.
Here is a fairly representative bit of code:
// test class library
namespace TestLibrary
{
public class TestClient
{
.
.
.
public async Task<SomeResponse> DoAsyncWork()
{
// actual code happens to use Flurl which is a light wrapper around HttpClient
string baseUrl = @"https://api.somewhere.com/v1/testendpoint/";
string somedata = "some test data";
var response = await baseUrl
.WithHeader("Content-Type", "application/json")
.PostStringAsync(somedata)
.ReceiveJson<SomeResponse>()
.ConfigureAwait(false);
return response;
}
}
.
.
.
}
. . .
// in ASP.NET webforms site
// .NET Framework 4.8
// Page directive includes Async="true"
protected async void btnTest_Click(object sender, EventArgs e)
{
TestClient client = new TestClient();
SomeResponse response = await client.DoAsyncWork();
// do something with the response (update database, whatever)
// ... all working so far ...
// now go to another page
// (for example, for extended messaging or another "step" in the process)
// this "works" in that the user is redirected to the right page, but...
// "Thread was being aborted" error is caught and logged (global exception handler implemented)
Response.Redirect("somepage.aspx");
}
.
.
.
I realize I could ignore the error (or perhaps rework it so there is no redirect), but what I'm wondering is if there is a "right" way to do this.
I should mention that I have tried passing in a boolean (false) to the Redirect call and that does circumvent the exception (although that does introduce other potential "gotchas"...).
I'm just "concerned" that reason we're getting a Thread Abort error here (and not on other pages that don't do async) is that there's an "uncompleted" task of some sort. Or that I'm not "waiting" in the right way...
I have read many articles by Stephen Cleary, but if you'll pardon the pun, I am not very clear on structuring up async/await code in ASP.NET webforms ... yet!