我开始实现一个基本的C#服务器,它将处理POST和GET。
我有以下内容:
private static HttpListener listener;
private static void CreateListener()
{
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:1234/");
listener.Start();
listener.BeginGetContext(Process, listener);
Console.WriteLine("Listening...");
}
private static void Process(IAsyncResult result)
{
HttpListenerContext context = listener.EndGetContext(result);
listener.BeginGetContext(Process, listener);
Console.WriteLine(context);
Console.ReadLine();
}
尝试使用基本的httpWebRequest
:
private static void Post(string webAddress)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddress);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize("Some POSTed Data");
streamWriter.Write(json);
streamWriter.Flush();
}
}
public static void Main(string[] args)
{
CreateListener();
Post("http://localhost:1234/");
Console.WriteLine("Got here!!");
Console.ReadLine();
}
但它似乎没有触发Process
功能。那是为什么?