Last active
October 3, 2018 15:03
-
-
Save mniak/0ed6c42c82d9032973f7fb8c65ed9a92 to your computer and use it in GitHub Desktop.
#owin single #http request listener.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Owin; | |
using Microsoft.Owin.Hosting; | |
using Owin; | |
using System; | |
using System.Threading.Tasks; | |
/* Used NuGet Packages | |
install-package Microsoft.Owin | |
install-package Microsoft.Owin.Host.HttpListener | |
install-package Microsoft.Owin.Hosting | |
install-package Owin | |
*/ | |
public class SingleRequestListener : IDisposable | |
{ | |
private readonly string url; | |
private readonly TaskCompletionSource<IOwinRequest> completionSource; | |
private IDisposable webApp; | |
public SingleRequestListener(string url) | |
{ | |
this.url = url; | |
completionSource = new TaskCompletionSource<IOwinRequest>(); | |
} | |
public Task<IOwinRequest> ListenRequest() | |
{ | |
CheckDisposed(); | |
var startOptions = new StartOptions(); | |
startOptions.Urls.Add(url); | |
webApp = WebApp.Start(startOptions, app => app.Run(HandleRequest)); | |
Console.WriteLine("Waiting"); | |
return completionSource.Task; | |
} | |
public static Task<IOwinRequest> ListenRequest(string url) | |
{ | |
return new SingleRequestListener(url).ListenRequest(); | |
} | |
private bool handled = false; | |
private readonly object lockHandled = new object(); | |
private async Task HandleRequest(IOwinContext ctx) | |
{ | |
lock (lockHandled) | |
{ | |
if (handled) return; | |
handled = true; | |
} | |
await Task.Yield(); | |
completionSource.SetResult(ctx.Request); | |
Dispose(); | |
} | |
private void CheckDisposed() | |
{ | |
if (disposed) | |
throw new ObjectDisposedException(GetType().FullName); | |
} | |
private bool disposed = false; | |
public void Dispose() | |
{ | |
if (webApp != null) | |
{ | |
webApp.Dispose(); | |
disposed = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment