本文整理汇总了C#中System.Net.HttpListener.EndGetContext方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListener.EndGetContext方法的具体用法?C# HttpListener.EndGetContext怎么用?C# HttpListener.EndGetContext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpListener
的用法示例。
在下文中一共展示了HttpListener.EndGetContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Start
public void Start(string bindUrl)
{
Ensure.NotNull(bindUrl, nameof(bindUrl));
_httpListener = new HttpListener { IgnoreWriteExceptions = false };
_httpListener.Prefixes.Add(bindUrl);
_httpListener.Start();
AsyncCallback acceptConnection = null;
acceptConnection = state =>
{
try
{
HttpListenerContext clientContext = _httpListener.EndGetContext(state);
Log.Info($"New Ecr connection from: {clientContext.Request.RemoteEndPoint}");
ProcessAsync(clientContext);
}
catch (Exception ex)
{
Log.Error(ex);
}
finally
{
_httpListener.BeginGetContext(acceptConnection, null);
}
};
_httpListener.BeginGetContext(acceptConnection, null);
RegisterActions();
}
示例2: StartTestServer
/// <summary>
/// Creates a simple server to test the tunnel
/// </summary>
/// <param name="listenUrl"></param>
/// <param name="expectedResponse"></param>
/// <returns></returns>
private HttpListener StartTestServer(string listenUrl, string expectedResponse)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add(listenUrl);
listener.Start();
listener.BeginGetContext(new AsyncCallback((result) =>
{
HttpListener listenr = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string responseString = expectedResponse;
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}), listener);
listener.Start();
return listener;
}
示例3: HTTPServer
public HTTPServer()
{
listener = new HttpListener();
listener.Prefixes.Add("http://*:" + WebAPI.dis.Configuration.Instance.Port + "/");
listener.Start();
WhitelistIPs = new List<string>() { };
if(WebAPI.dis.Configuration.Instance.WhitelistIPs.Count > 0)
{
foreach(var ip in WebAPI.dis.Configuration.Instance.WhitelistIPs)
{
WhitelistIPs.Add(ip.IP);
}
}
AsyncCallback callback = null;
callback = ar =>
{
if (!listener.IsListening)
return;
new Thread(() =>
{
this.ProcessClient(
listener.EndGetContext(ar)
);
}).Start();
listener.BeginGetContext(callback, null);
};
listener.BeginGetContext(callback, null);
}
示例4: InitialUnicastEventTest
public void InitialUnicastEventTest ()
{
var eventer = new DummyStateVariableEventer ();
var root = CreateRoot (CreateServiceController (new StateVariable ("Foo", "string", new StateVariableOptions { Eventer = eventer })));
eventer.SetValue ("foo");
using (var server = new Server (root)) {
server.Start ();
var prefix = GeneratePrefix ();
using (var listener = new HttpListener ()) {
listener.Prefixes.Add (prefix);
listener.Start ();
Exception exception = null;
listener.BeginGetContext (result => {
try {
var context = listener.EndGetContext (result);
using (var reader = new StreamReader (context.Request.InputStream)) {
Assert.AreEqual (Xml.SingleEventReport, reader.ReadToEnd ());
}
context.Response.Close ();
} catch (Exception e) {
exception = e;
}
lock (mutex) {
Monitor.Pulse (mutex);
}
}, null);
Subscribe (root, prefix);
if (exception != null) {
throw exception;
}
}
}
}
示例5: UnsubscribeUnicastEventTest
public void UnsubscribeUnicastEventTest ()
{
string sid = null;
var eventer = new DummyStateVariableEventer ();
var root = CreateRoot (CreateServiceController (new StateVariable ("Foo", "string", new StateVariableOptions { Eventer = eventer })));
eventer.SetValue ("foo");
using (var server = new Server (root)) {
server.Start ();
var prefix = GeneratePrefix ();
var url = new Uri (root.UrlBase, "/service/0/event/");
using (var listener = new HttpListener ()) {
listener.Prefixes.Add (prefix);
listener.Start ();
Exception exception = null;
listener.BeginGetContext (result => {
lock (mutex) {
try {
var context = listener.EndGetContext (result);
using (var reader = new StreamReader (context.Request.InputStream)) {
Assert.AreEqual (Xml.SingleEventReport, reader.ReadToEnd ());
}
context.Response.Close ();
var unsub_request = WebRequest.Create (url);
unsub_request.Method = "UNSUBSCRIBE";
unsub_request.Headers.Add ("SID", sid);
using (var response = (HttpWebResponse)unsub_request.GetResponse ()) {
Assert.AreEqual (HttpStatusCode.OK, response.StatusCode);
}
listener.BeginGetContext (r => {
lock (mutex) {
Monitor.Pulse (mutex);
}
}, null);
eventer.SetValue ("foo");
} catch (Exception e) {
exception = e;
Monitor.Pulse (mutex);
}
}
}, null);
var request = WebRequest.Create (url);
request.Method = "SUBSCRIBE";
request.Headers.Add ("CALLBACK", string.Format ("<{0}>", prefix));
request.Headers.Add ("NT", "upnp:event");
lock (mutex) {
using (var response = (HttpWebResponse)request.GetResponse ()) {
Assert.AreEqual (HttpStatusCode.OK, response.StatusCode);
Assert.IsNotNull (response.Headers["SID"]);
sid = response.Headers["SID"];
}
if (Monitor.Wait (mutex, TimeSpan.FromSeconds (10))) {
Assert.Fail ("The event server sent updates to an unsubscribed client.");
}
}
if (exception != null) {
throw exception;
}
}
}
}
示例6: ServeStaticContent
private void ServeStaticContent ()
{
if (Debug) Console.WriteLine ();
if (Debug) Console.WriteLine ("Serving static content...");
listener = new HttpListener ();
listener.Prefixes.Add (BaseUrl);
listener.Start ();
serving = true;
while (!stop_requested) {
var async_result = listener.BeginGetContext (result => {
var context = listener.EndGetContext (result);
var response = context.Response;
var path = context.Request.Url.LocalPath;
response.StatusCode = 200;
response.StatusDescription = "OK";
response.ProtocolVersion = new Version ("1.1");
try {
if (Debug) Console.WriteLine ("Serving: {0}", path);
if (path == "/") {
ServeString (response, resources.Count.ToString () + "\n");
return;
} else if (path == "/shutdown") {
ServeString (response, "Goodbye\n");
lock (this) {
stop_requested = true;
}
}
var resource = resources[Int32.Parse (path.Substring (1))];
response.ContentType = "application/octet-stream";
response.ContentLength64 = resource.Length;
response.AppendHeader ("X-Content-MD5-Sum", resource.Checksum);
if (context.Request.HttpMethod == "HEAD") {
response.Close ();
}
using (var resource_stream = File.OpenRead (resource.Path)) {
var buffer = new byte[32 << 10];
using (response.OutputStream) {
while (true) {
var read = resource_stream.Read (buffer, 0, buffer.Length);
if (read <= 0) {
break;
}
response.OutputStream.Write (buffer, 0, read);
}
}
}
} catch {
response.StatusCode = 404;
response.StatusDescription = "404 Not Found";
ServeString (response, "Invalid resource: " + path + "\n");
}
response.Close ();
}, null);
async_result.AsyncWaitHandle.WaitOne ();
}
}
示例7: Create
public static IDisposable Create(AppDelegate app, int port, string path)
{
app = ErrorPage.Middleware(app);
var effectivePath = path ?? "";
if (!effectivePath.EndsWith("/"))
effectivePath += "/";
var listener = new System.Net.HttpListener();
listener.Prefixes.Add(string.Format("http://+:{0}{1}", port, effectivePath));
listener.Start();
Action go = () => { };
go = () => listener.BeginGetContext(
ar =>
{
HttpListenerContext context;
try
{
context = listener.EndGetContext(ar);
}
finally
{
// ReSharper disable AccessToModifiedClosure
go();
// ReSharper restore AccessToModifiedClosure
}
var requestPathBase = effectivePath;
if (requestPathBase == "/" || requestPathBase == null)
requestPathBase = "";
var requestPath = context.Request.Url.AbsolutePath;
if (string.IsNullOrEmpty(requestPath))
requestPath = "/";
if (requestPath.StartsWith(requestPathBase, StringComparison.OrdinalIgnoreCase))
requestPath = requestPath.Substring(requestPathBase.Length);
var requestQueryString = context.Request.Url.GetComponents(UriComponents.Query, UriFormat.UriEscaped);
var requestHeaders = context.Request.Headers.AllKeys
.ToDictionary(x => x, x => (IEnumerable<string>)context.Request.Headers.GetValues(x), StringComparer.OrdinalIgnoreCase);
var env = new Dictionary<string, object>
{
{OwinConstants.Version, "1.0"},
{OwinConstants.RequestMethod, context.Request.HttpMethod},
{OwinConstants.RequestScheme, context.Request.Url.Scheme},
{OwinConstants.RequestPathBase, requestPathBase},
{OwinConstants.RequestPath, requestPath},
{OwinConstants.RequestQueryString, requestQueryString},
{OwinConstants.RequestHeaders, requestHeaders},
{OwinConstants.RequestBody, RequestBody(context.Request.InputStream)},
{"System.Net.HttpListenerContext", context},
{"server.CLIENT_IP", context.Request.RemoteEndPoint.Address.ToString()},
};
app(env,
(status, headers, body) =>
{
context.Response.StatusCode = int.Parse(status.Substring(0, 3));
context.Response.StatusDescription = status.Substring(4);
foreach (var kv in headers)
{
// these may not be assigned via header collection
if (string.Equals(kv.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
{
context.Response.ContentLength64 = long.Parse(kv.Value.Single());
}
else if (string.Equals(kv.Key, "Keep-Alive", StringComparison.OrdinalIgnoreCase))
{
context.Response.KeepAlive = true;
}
//else if (string.Equals(kv.Key, "Transfer-Encoding", StringComparison.OrdinalIgnoreCase))
//{
// // not sure what can be done about this
//}
//else if (string.Equals(kv.Key, "WWW-Authenticate", StringComparison.OrdinalIgnoreCase))
//{
// // not sure what httplistener properties to assign
//}
else
{
// all others are
foreach (var v in kv.Value)
{
context.Response.Headers.Add(kv.Key, v);
}
}
}
var pipeResponse = new PipeResponse(
context.Response.OutputStream,
ex => context.Response.Close(),
() => context.Response.Close());
pipeResponse.Go(body);
},
ex =>
{
// This should never be called
throw new NotImplementedException();
//.........这里部分代码省略.........
示例8: HttpClientIsDisconnectedCheckForWriteException
public void HttpClientIsDisconnectedCheckForWriteException()
{
string uri = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";
AutoResetEvent exceptionOccuredEvent = new AutoResetEvent (false);
HttpListener listener = new HttpListener {
IgnoreWriteExceptions = false
};
listener.Prefixes.Add (uri);
listener.Start ();
listener.BeginGetContext (result =>
{
HttpListenerContext context = listener.EndGetContext (result);
context.Response.SendChunked = true;
context.Request.InputStream.Close ();
var bytes = new byte [1024];
using(Stream outputStream = context.Response.OutputStream) {
try {
while (true)
outputStream.Write (bytes, 0, bytes.Length);
} catch {
exceptionOccuredEvent.Set ();
}
}
}, null);
Task.Factory.StartNew (() =>
{
var webRequest = (HttpWebRequest)WebRequest.Create (uri);
webRequest.Method = "POST";
webRequest.KeepAlive = false;
Stream requestStream = webRequest.GetRequestStream ();
requestStream.WriteByte (1);
requestStream.Close ();
using (WebResponse response = webRequest.GetResponse ())
using (Stream stream = response.GetResponseStream ()) {
byte[] clientBytes = new byte [1024];
Assert.IsNotNull (stream, "#01");
stream.Read (clientBytes, 0, clientBytes.Length);
}
});
Assert.IsTrue (exceptionOccuredEvent.WaitOne (15 * 1000), "#02");
}
示例9: AddListenerContext
HttpListener AddListenerContext (HttpListener l, Action<HttpListenerContext> contextAssert)
{
l.BeginGetContext (ar => {
var ctx = l.EndGetContext (ar);
try {
if (contextAssert != null)
contextAssert (ctx);
} finally {
ctx.Response.Close ();
}
}, null);
return l;
}
示例10: CreateListener
HttpListener CreateListener (Action<HttpListenerContext> contextAssert)
{
var l = new HttpListener ();
l.Prefixes.Add (string.Format ("http://+:{0}/", port));
l.Start ();
l.BeginGetContext (ar => {
var ctx = l.EndGetContext (ar);
try {
if (contextAssert != null)
contextAssert (ctx);
} finally {
ctx.Response.Close ();
}
}, null);
return l;
}
示例11: Create
public static IDisposable Create(AppDelegate app, int port, string path)
{
app = ErrorPage.Middleware(app);
var effectivePath = path ?? "";
if (!effectivePath.EndsWith("/"))
effectivePath += "/";
var listener = new System.Net.HttpListener();
listener.Prefixes.Add(string.Format("http://+:{0}{1}", port, effectivePath));
listener.Start();
Action go = () => { };
go = () => listener.BeginGetContext(
ar =>
{
HttpListenerContext context;
try
{
context = listener.EndGetContext(ar);
}
finally
{
// ReSharper disable AccessToModifiedClosure
go();
// ReSharper restore AccessToModifiedClosure
}
CallParameters call;
var requestPathBase = effectivePath;
if (requestPathBase == "/" || requestPathBase == null)
requestPathBase = "";
var requestPath = context.Request.Url.AbsolutePath;
if (string.IsNullOrEmpty(requestPath))
requestPath = "/";
if (requestPath.StartsWith(requestPathBase, StringComparison.OrdinalIgnoreCase))
requestPath = requestPath.Substring(requestPathBase.Length);
var requestQueryString = context.Request.Url.GetComponents(UriComponents.Query, UriFormat.UriEscaped);
call.Headers = context.Request.Headers.AllKeys
.ToDictionary(x => x, x => context.Request.Headers.GetValues(x), StringComparer.OrdinalIgnoreCase);
call.Environment = new Dictionary<string, object>
{
{OwinConstants.Version, "1.0"},
{OwinConstants.RequestMethod, context.Request.HttpMethod},
{OwinConstants.RequestScheme, context.Request.Url.Scheme},
{OwinConstants.RequestPathBase, requestPathBase},
{OwinConstants.RequestPath, requestPath},
{OwinConstants.RequestQueryString, requestQueryString},
{"System.Net.HttpListenerContext", context},
};
call.Body = context.Request.InputStream;
try
{
Task<ResultParameters> appTask = app(call);
// No real error handling, just close the connection.
appTask.ContinueWith(task => context.Response.Abort(), TaskContinuationOptions.NotOnRanToCompletion);
// Success
appTask.Then(
result =>
{
context.Response.StatusCode = result.Status;
// context.Response.StatusDescription = ;
foreach (var kv in result.Headers)
{
// these may not be assigned via header collection
if (string.Equals(kv.Key, "Content-Length", StringComparison.OrdinalIgnoreCase))
{
context.Response.ContentLength64 = long.Parse(kv.Value.Single());
}
else if (string.Equals(kv.Key, "Keep-Alive", StringComparison.OrdinalIgnoreCase))
{
context.Response.KeepAlive = true;
}
//else if (string.Equals(kv.Key, "Transfer-Encoding", StringComparison.OrdinalIgnoreCase))
//{
// // not sure what can be done about this
//}
//else if (string.Equals(kv.Key, "WWW-Authenticate", StringComparison.OrdinalIgnoreCase))
//{
// // not sure what httplistener properties to assign
//}
else
{
// all others are
foreach (var v in kv.Value)
{
context.Response.Headers.Add(kv.Key, v);
}
}
}
//.........这里部分代码省略.........
示例12: Main
static void Main(string[] args)
{
WebUtils.DefaultTimeout = 10000;
WebUtils.NumRetries = 3;
WebUtils.WaitBetweenRetries = 5000;
WebUtils.ReadWriteTimeout = 30000;
ServicePointManager.DefaultConnectionLimit = 8;
DateTime startTime = DateTime.MinValue;
Logger rootLogger = Logger.GetRootLogger();
rootLogger.LocalLevel = Logger.Level.Debug;
string LOG_FILE_NAME = ConfigurationManager.AppSettings["logFileName"];
rootLogger.LocalOutputType = Logger.OutputType.Console;
if (LOG_FILE_NAME != null)
{
rootLogger.LocalOutputWriter = new StreamWriter(LOG_FILE_NAME, /*append=*/true);
rootLogger.LocalOutputType |= Logger.OutputType.Writer;
}
string SOURCES_FILE_NAME = ConfigurationManager.AppSettings["dataSourcesFileName"];
string WEB_SITE_ID = Utils.GetConfigValue("webSiteId", "dacq");
string DB_CONNECTION_STRING = ConfigurationManager.AppSettings["dbConnectionString"];
string SQL_DB_CONNECTION_STRING = ConfigurationManager.AppSettings["SqlDbConnectionString"];
string DB_CONNECTION_STRING_DUMP = ConfigurationManager.AppSettings["dbConnectionStringDump"];
string CLIENT_IP = ConfigurationManager.AppSettings["clientIp"];
string XML_DATA_ROOT = ConfigurationManager.AppSettings["xmlDataRoot"];
string XML_DATA_ROOT_DUMP = ConfigurationManager.AppSettings["xmlDataRootDump"];
string HTML_DATA_ROOT = ConfigurationManager.AppSettings["htmlDataRoot"];
string HTML_DATA_ROOT_DUMP = ConfigurationManager.AppSettings["htmlDataRootDump"];
string XML_DATA_ROOT_NEW = XML_DATA_ROOT == null ? null : (XML_DATA_ROOT.TrimEnd('\\') + "\\" + "New");
string HTML_DATA_ROOT_NEW = HTML_DATA_ROOT == null ? null : (HTML_DATA_ROOT.TrimEnd('\\') + "\\" + "New");
string XML_DATA_ROOT_DUMP_NEW = XML_DATA_ROOT_DUMP == null ? null : (XML_DATA_ROOT_DUMP.TrimEnd('\\') + "\\" + "New");
string HTML_DATA_ROOT_DUMP_NEW = HTML_DATA_ROOT_DUMP == null ? null : (HTML_DATA_ROOT_DUMP.TrimEnd('\\') + "\\" + "New");
string DB_CONNECTION_STRING_NEW = ConfigurationManager.AppSettings["SqlDbConnectionStringNew"];
string tmp = ConfigurationManager.AppSettings["enableZeroMQ"];
bool ENABLE_ZEROMQ = tmp != null && new List<string>(new string[] { "true", "1", "yes", "on" }).Contains(tmp.ToLower());
const int NUM_WRITERS = 8;
const int SLEEP_BETWEEN_POLLS = 15 * 60000; // 15 minutes
ArrayList<StreamDataProducerPoll> dataReaders = new ArrayList<StreamDataProducerPoll>();
ArrayList<StreamDataConsumer> dataConsumers = new ArrayList<StreamDataConsumer>();
Dictionary<IWorkflowComponent, Guid> components = new Dictionary<IWorkflowComponent, Guid>();
// init logging
Logger logger = Logger.GetLogger("Latino.Workflows.Dacq");
// start HTTP server
bool exit = false;
bool httpServerRunning = false;
if (CLIENT_IP != null)
{
new Thread(new ThreadStart(delegate()
{
HttpListener listener = new HttpListener();
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
listener.Prefixes.Add(string.Format("http://localhost/{0}/", WEB_SITE_ID));
listener.Prefixes.Add(string.Format("http://first.ijs.si/{0}/", WEB_SITE_ID));
listener.Start();
logger.Info("Main.HttpServer", "HTTP server started.");
httpServerRunning = true;
DateTime prevRequestTime = DateTime.MinValue;
while (!exit)
{
try
{
HttpListenerContext ctx = null;
listener.BeginGetContext(new AsyncCallback(delegate(IAsyncResult ar)
{
try { ctx = listener.EndGetContext(ar); }
catch { }
}), /*state=*/null);
while (!exit && ctx == null) { Thread.Sleep(500); }
if (!exit)
{
// process requests one by one
ctx.Response.AppendHeader("Content-Type", "application/xml");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.CheckCharacters = false;
settings.Indent = true;
XmlWriter w = XmlTextWriter.Create(ctx.Response.OutputStream, settings);
w.WriteStartElement("DacqResponse");
w.WriteElementString("DacqStartTime", startTime.ToString(TIME_FORMAT));
if (prevRequestTime == DateTime.MinValue) { prevRequestTime = startTime; }
DateTime thisRequestTime = DateTime.Now;
string command = GetHttpRequestCommand(ctx.Request.Url.ToString());
if (command == "components")
{
w.WriteElementString("PreviousRequestTime", prevRequestTime.ToString(TIME_FORMAT));
w.WriteElementString("ThisRequestTime", thisRequestTime.ToString(TIME_FORMAT));
}
w.WriteElementString("Request", ctx.Request.Url.ToString());
w.WriteElementString("Command", command);
w.WriteStartElement("ResponseBody");
if (command == "help")
{
WriteSupportedCommands(w);
}
else if (command == "components")
{
WriteComponentInfo(w, components, thisRequestTime, prevRequestTime);
prevRequestTime = thisRequestTime;
}
else if (command == "sources")
//.........这里部分代码省略.........
示例13: Login
private void Login()
{
myLifetimes.Next(lifetime =>
{
myClient.UserLogin = null;
myClient.GetTokenAsync(
login =>
{
var tcpListener = new TcpListener(IPAddress.Loopback, 0);
int port;
try
{
tcpListener.Start();
port = ((IPEndPoint) tcpListener.LocalEndpoint).Port;
}
finally
{
tcpListener.Stop();
}
var callbackUri = string.Format("http://{0}:{1}/", "localhost", port);
var server = new HttpListener();
server.Prefixes.Add(callbackUri);
server.Start();
lifetime.AddDispose(server);
server.BeginGetContext(ar =>
{
myClient.Logger.CatchAsOuterDataError(() =>
{
if (lifetime.IsTerminated) return;
var context = server.EndGetContext(ar);
// Write a response.
using (var writer = new StreamWriter(context.Response.OutputStream))
{
string response = @"<html>
<head>
<title>JetBox - OAuth Authentication</title>
</head>
<body>
<h1>Authorization for JetBox</h1>
<p>The application has received your response. You can close this window now.</p>
<script type='text/javascript'>
window.setTimeout(function() { window.open('', '_self', ''); window.close(); }, 100);
if (window.opener) { window.opener.checkToken(); }
</script>
</body>
</html>";
writer.WriteLine(response);
writer.Flush();
}
context.Response.OutputStream.Flush();
context.Response.OutputStream.Close();
context.Response.Close();
GetInfo();
});
}, null);
Environment.OpensUri.OpenUri(new Uri(myClient.BuildAuthorizeUrl(callbackUri)));
},
myClient.LogException);
});
}
示例14: startLocalServer
/// <summary>
/// Starts the local server.
/// </summary>
private void startLocalServer()
{
// Start the server on localhost.
canExit = false;
newHttpListener = new System.Net.HttpListener();
newHttpListener.Prefixes.Add(LOCALHOST_ADDRESS);
newHttpListener.Start();
// Start the listener.
serverThread = new Thread(delegate() {
while (!canExit) {
IAsyncResult serverWaitHandle = newHttpListener.BeginGetContext(
new AsyncCallback(handlePageRequest), newHttpListener);
bool waitResult = serverWaitHandle.AsyncWaitHandle.WaitOne(1000);
if (waitResult) {
newHttpListener.EndGetContext(serverWaitHandle);
}
}
});
serverThread.Start();
}
示例15: UserHeaderWithDoubleMultiValue
public void UserHeaderWithDoubleMultiValue ()
{
string uri = "http://localhost:" + NetworkHelpers.FindFreePort () + "/";
var l = new HttpListener ();
l.Prefixes.Add (uri);
l.Start ();
l.BeginGetContext (ar => {
var ctx = l.EndGetContext (ar);
var response = ctx.Response;
response.Headers.Add ("X-Custom-Header", "A");
response.Headers.Add ("X-Custom-Header", "B");
response.Close ();
}, null);
HttpWebRequest wr = HttpWebRequest.CreateHttp (uri);
var resp = wr.GetResponse ();
var vls = resp.Headers.GetValues ("X-Custom-Header");
Assert.AreEqual (2, vls.Length);
l.Close ();
}