本文整理汇总了C#中System.Net.HttpListenerContext类的典型用法代码示例。如果您正苦于以下问题:C# HttpListenerContext类的具体用法?C# HttpListenerContext怎么用?C# HttpListenerContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpListenerContext类属于System.Net命名空间,在下文中一共展示了HttpListenerContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ProcessRequest
static void ProcessRequest(HttpListenerContext context)
{
try
{
IRequestHandler handler;
if (!RequestHandlers.Handlers.TryGetValue(context.Request.Url.LocalPath, out handler))
{
context.Response.StatusCode = 400;
context.Response.StatusDescription = "Bad request";
using (StreamWriter wtr = new StreamWriter(context.Response.OutputStream))
wtr.Write("<h1>Bad request</h1>");
}
else
handler.HandleRequest(context);
}
catch (Exception e)
{
using (StreamWriter wtr = new StreamWriter(context.Response.OutputStream))
wtr.Write("<Error>Internal Server Error</Error>");
Console.Error.WriteLine(e);
}
context.Response.Close();
}
示例2: HandleRequest
public override void HandleRequest(HttpListenerContext context)
{
NameValueCollection query;
using (var rdr = new StreamReader(context.Request.InputStream))
query = HttpUtility.ParseQueryString(rdr.ReadToEnd());
using (var db = new Database(Program.Settings.GetValue("conn")))
{
Account acc = db.Verify(query["guid"], query["password"]);
byte[] status;
if (acc == null)
status = Encoding.UTF8.GetBytes("<Error>Account credentials not valid</Error>");
else
{
try
{
status = Encoding.UTF8.GetBytes(db.GetGuildBoard(acc));
}
catch (Exception e)
{
status = Encoding.UTF8.GetBytes("<Error>" + e.Message + "</Error>");
}
}
context.Response.OutputStream.Write(status, 0, status.Length);
}
}
示例3: AccountUserTypeHandler
private static void AccountUserTypeHandler(HttpListenerContext context)
{
switch (context.Request.RawUrl)
{
case "/api/v1/accounts/usertypes":
if (context.Request.HttpMethod == "GET")
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.OutputStream.Write(expectedUserTypesResponse);
}
else if (context.Request.HttpMethod == "PUT")
{
requestContent = context.Request.GetRequestAsString();
if (context.Request.Headers.AllKeys.Any(c => c == ApiUrls.AuthorizeTokenHeaderName))
context.Response.StatusCode = (int)HttpStatusCode.NoContent;
else
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
break;
case "/api/authorize":
context.Response.Headers.Add(ApiUrls.AuthorizeTokenHeaderName, "OK");
break;
default:
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
break;
}
}
示例4: HandleRequest
public override void HandleRequest(HttpListenerContext context)
{
NameValueCollection query;
using (var rdr = new StreamReader(context.Request.InputStream))
query = HttpUtility.ParseQueryString(rdr.ReadToEnd());
using (var db = new Database(Program.Settings.GetValue("conn")))
{
Account acc = db.Verify(query["guid"], query["password"]);
byte[] status;
if (acc == null)
status = Encoding.UTF8.GetBytes("<Error>Account credentials not valid</Error>");
else
{
MySqlCommand cmd = db.CreateQuery();
cmd.CommandText = @"DELETE FROM characters WHERE accId = @accId AND charId = @charId;";
cmd.Parameters.AddWithValue("@accId", acc.AccountId);
cmd.Parameters.AddWithValue("@charId", query["charId"]);
if (cmd.ExecuteNonQuery() > 0)
status = Encoding.UTF8.GetBytes("<Success />");
else
status = Encoding.UTF8.GetBytes("<Error>Internal Error</Error>");
}
context.Response.OutputStream.Write(status, 0, status.Length);
}
}
示例5: ProcessRequest
static void ProcessRequest(HttpListenerContext context)
{
Console.WriteLine("{0} {1} {2}", DateTime.UtcNow.ToString("o"), context.Request.HttpMethod, context.Request.Url.PathAndQuery);
var service = GetService(context.Request.Url.PathAndQuery);
context.Response.Headers["Content-Type"] = String.Format("application/x-git-{0}-advertisement", service);
context.Response.Headers["Expires"] = "Fri, 01 Jan 1980 00:00:00 GMT";
context.Response.Headers["Pragma"] = "no-cache";
context.Response.Headers["Cache-Control"] = "no-cache, max-age=0, must-revalidate";
if (context.Request.HttpMethod == "GET" && context.Request.Url.AbsolutePath == "/info/refs")
{
var input = String.Format("# service=git-{0}\n", service);
var toWrite = (input.Length + 4).ToString("x").PadLeft(4, '0') + input;
context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(toWrite), 0, Encoding.UTF8.GetByteCount(toWrite));
toWrite = "0000";
context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(toWrite), 0, Encoding.UTF8.GetByteCount(toWrite));
var exe = new Executable();
var args = String.Format("{0} --stateless-rpc --advertise-refs \"{1}\"", service, Program.RepositoryPath);
exe.ExecuteAsync(args, context.Response.OutputStream).Wait();
context.Response.Close();
}
else
{
var exe = new Executable();
var args = String.Format("{0} --stateless-rpc \"{1}\"", service, Program.RepositoryPath);
exe.ExecuteAsync(args, context.Response.OutputStream, GetInputStream(context.Request)).Wait();
context.Response.Close();
}
}
示例6: HttpListenerContextAdapter
public HttpListenerContextAdapter(HttpListenerContext inner)
{
_inner = inner;
Request = new HttpListenerRequestAdapter(inner.Request);
Response = new HttpListenerResponseAdapter(inner.Response);
Items = new HybridDictionary(true);
}
示例7: ProcessRequestAsync
protected override Task ProcessRequestAsync(HttpListenerContext context)
{
if (string.IsNullOrEmpty(context.Request.RawUrl))
return ((object)null).AsTaskResult();
var operationName = context.Request.GetOperationName().UrlDecode();
var httpReq = context.ToRequest(operationName);
var httpRes = httpReq.Response;
var handler = HttpHandlerFactory.GetHandler(httpReq);
var serviceStackHandler = handler as IServiceStackHandler;
if (serviceStackHandler != null)
{
var restHandler = serviceStackHandler as RestHandler;
if (restHandler != null)
{
httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName();
}
var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName);
task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent);
//Matches Exceptions handled in HttpListenerBase.InitTask()
return task;
}
return new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo)
.AsTaskException();
}
示例8: ReadBodyFromRequest
public static Body ReadBodyFromRequest(HttpListenerContext ctx)
{
if (ctx == null) throw new ArgumentNullException("ctx");
try
{
if (!ctx.Request.HasEntityBody) return null;
byte[] data = new byte[ctx.Request.ContentLength64];
int offset = 0;
int count = data.Length;
// Read may return anything from 0 to ContentLength64.
while (0 < count)
{
int readed = ctx.Request.InputStream.Read(data, offset, count);
if (readed == 0) break;
offset += readed;
count -= readed;
}
NetStatistics.ReadBytes(count);
return ElementSerializer.DeSerializeElement<Body>(Encoding.UTF8.GetString(data));
}
catch (Exception e)
{
if (e is HttpListenerException || e is ObjectDisposedException)
{
// ignore
}
else
{
log.ErrorFormat("Error read body from request: {0}", e);
}
}
return null;
}
示例9: SolveAsync
static async void SolveAsync(HttpListenerContext context)
{
Console.WriteLine("New great task!");
try
{
var arr = Converter.ToList(context.Request.InputStream);
// arr.ForEach(x => Console.Write("{0} ", x));
// Console.WriteLine();
arr.Sort();
// arr.ForEach(x => Console.Write("{0} ", x));
// Console.WriteLine();
var bytes = Converter.ToBytes(arr);
await context.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
context.Response.Close();
Console.WriteLine("Sended");
}
catch(Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
示例10: HandleRequest
public void HandleRequest(HttpListenerContext context)
{
NameValueCollection query;
using (var rdr = new StreamReader(context.Request.InputStream))
query = HttpUtility.ParseQueryString(rdr.ReadToEnd());
using (var db = new Database())
{
Account acc = db.Verify(query["guid"], query["password"]);
byte[] status;
if (acc == null)
status = Encoding.UTF8.GetBytes("<Error>Bad login</Error>");
else
{
try
{
status =
Encoding.UTF8.GetBytes(db.HttpGetGuildMembers(Convert.ToInt32(query["num"]),
Convert.ToInt32(query["offset"]), acc));
}
catch
{
status = Encoding.UTF8.GetBytes("<Error>Guild member error</Error>");
}
}
context.Response.OutputStream.Write(status, 0, status.Length);
context.Response.Close();
}
}
示例11: HandleRequest
public void HandleRequest(HttpListenerContext context)
{
NameValueCollection query;
using (var rdr = new StreamReader(context.Request.InputStream))
query = HttpUtility.ParseQueryString(rdr.ReadToEnd());
using (var db = new Database())
{
List<ServerItem> filteredServers = null;
Account a = db.Verify(query["guid"], query["password"]);
if (a != null)
{
if (a.Banned)
{
filteredServers = YoureBanned();
}
else
{
filteredServers = GetServersForRank(a.Rank);
}
}
else
{
filteredServers = GetServersForRank(0);
}
var chrs = new Chars
{
Characters = new List<Char>(),
NextCharId = 2,
MaxNumChars = 1,
Account = db.Verify(query["guid"], query["password"]),
Servers = filteredServers
};
Account dvh = null;
if (chrs.Account != null)
{
db.GetCharData(chrs.Account, chrs);
db.LoadCharacters(chrs.Account, chrs);
chrs.News = db.GetNews(chrs.Account);
dvh = chrs.Account;
}
else
{
chrs.Account = Database.CreateGuestAccount(query["guid"]);
chrs.News = db.GetNews(null);
}
var ms = new MemoryStream();
var serializer = new XmlSerializer(chrs.GetType(),
new XmlRootAttribute(chrs.GetType().Name) {Namespace = ""});
var xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8;
XmlWriter xtw = XmlWriter.Create(context.Response.OutputStream, xws);
serializer.Serialize(xtw, chrs, chrs.Namespaces);
db.Dispose();
}
}
示例12: sendCommand
public static String sendCommand(HttpListenerContext context, String text)
{
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
String cookie = context.Request.Cookies["session"].Value;
CleverbotConversation activeConversation;
bool flag = false;
if (Sessions.active.ContainsKey(cookie))
{
activeConversation = Sessions.active[cookie];
}
else
{
activeConversation = Cleverbot.Cleverbot.buildSession(text);
flag = true;
Sessions.active.Add(cookie, activeConversation);
}
if (flag)
{
needToDo.Enqueue(activeConversation.latestReply.content);
return activeConversation.latestReply.content;
}
else
{
needToDo.Enqueue(activeConversation.speak(text).content);
return activeConversation.speak(text).content;
}
}
示例13: HandleRequest
public void HandleRequest(HttpListenerContext context)
{
NameValueCollection query;
using (StreamReader rdr = new StreamReader(context.Request.InputStream))
query = HttpUtility.ParseQueryString(rdr.ReadToEnd());
using (var db = new Database())
{
var acc = db.GetAccount(int.Parse(query["accountId"]));
var chr = db.LoadCharacter(acc, int.Parse(query["charId"]));
var cmd = db.CreateQuery();
cmd.CommandText = @"SELECT time, killer, firstBorn FROM death WHERE [email protected] AND [email protected];";
cmd.Parameters.AddWithValue("@accId", query["accountId"]);
cmd.Parameters.AddWithValue("@charId", query["charId"]);
int time;
string killer;
bool firstBorn;
using (var rdr = cmd.ExecuteReader())
{
rdr.Read();
time = Database.DateTimeToUnixTimestamp(rdr.GetDateTime("time"));
killer = rdr.GetString("killer");
firstBorn = rdr.GetBoolean("firstBorn");
}
using (StreamWriter wtr = new StreamWriter(context.Response.OutputStream))
wtr.Write(chr.FameStats.Serialize(acc, chr, time, killer, firstBorn));
}
}
示例14: GetSigningPage
private void GetSigningPage(HttpListenerContext context)
{
var signingKey = context.Request.Url.Query.TrimStart('?').Split('&')
.Select(t => t.Split('=')).ToDictionary(t => t[0], t => t[1]);
var html = string.Empty;
if (KeepSecretInServer)
{
html = System.IO.File.ReadAllText("EmbeddedSigningSample.secured.html")
.Replace("[AuthGenerator]", SampleParameters.GetAuthHeadersUrl)
.Replace("[ClientAccessTokenGenerator]", SampleParameters.GetClientAccessTokenUrl);
}
else
{
html = System.IO.File.ReadAllText("EmbeddedSigningSample.html")
.Replace("[APISecret]", SDKClient.APISecret);
};
html = html.Replace("[APIKEY]", SDKClient.APIKey)
.Replace("[APIServiceUrl]", SDKClient.ServiceBaseUrl)
.Replace("[APIVersion]", SDKClient.APIVersion)
.Replace("[SigningKey]", signingKey["key"]);
WriteResponse(context.Response, html);
System.Threading.Thread.Sleep(2000);
}
示例15: UsernamePasswordEchoHandler
private static void UsernamePasswordEchoHandler(HttpListenerContext context)
{
var header = context.Request.Headers["Authorization"];
var parts = Encoding.ASCII.GetString(Convert.FromBase64String(header.Substring("Basic ".Length))).Split(':');
context.Response.OutputStream.WriteStringUtf8(string.Join("|", parts));
}