I am trying to convert a route from an old controller based api to a new dotnet7 api, however for some reason the temporary endpoint is not being hold. The basic idea is to create a temporary endpoint inside the main endpoint, and if no one calls this endpoint, then it breaks the function. This has been so far experimental but we would like to see if we could put this to work.
Can someone help me converting this code?
old code:
public class EndpointController : ControllerBase
{
private bool endpointCalled = false;
private HttpListener listener;
[HttpGet]
public IActionResult Endpoint1()
{
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:7195/");
listener.Start();
// Create a temporary POST endpoint
listener.BeginGetContext(new AsyncCallback(Endpoint2), listener);
// Close the endpoint after 20 seconds if it has not been called
var timer = new Timer(20000);
timer.Elapsed += CloseEndpoint;
timer.Start();
return Results.Ok(new { message = "Endpoint2 created" });
}
private void Endpoint2(IAsyncResult result)
{
var context = listener.EndGetContext(result);
var request = context.Request;
var response = context.Response;
string responseString = "<HTML><BODY> Hello from Endpoint2!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
endpointCalled = true;
}
private void CloseEndpoint(object sender, ElapsedEventArgs e)
{
if (!endpointCalled)
{
listener.Stop();
}
}
}
new code:
app.MapPost("/supplier/listen2", () =>
{
bool endpointCalled = false;
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:7195/testi2/");
listener.Start();
listener.BeginGetContext(new AsyncCallback(Endpoint2), listener);
var timer = new System.Timers.Timer(20000);
timer.Elapsed += CloseEndpoint;
timer.Start();
void Endpoint2(IAsyncResult result)
{
var listener = (HttpListener)result.AsyncState;
var context = listener.EndGetContext(result);
var request = context.Request;
var response = context.Response;
string responseString = "<HTML><BODY> Hello from Endpoint2!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
endpointCalled = true;
}
void CloseEndpoint(object sender, System.Timers.ElapsedEventArgs e)
{
if (!endpointCalled)
{
listener.Stop();
}
}
return Results.Ok(new { message = "Endpoint2 created" });
// return Results.Ok(new { token = "-1" });
});
UPDATE:
Ok, there was an error before because I wrote the wrong port. Now I get an error because the listener is calling the already open door:
System.Net.HttpListenerException (48): Address already in use
Any tips to solve this?