我开始实现一个基本的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
功能。为什么?
您必须调用httpWebRequest.GetResponse()
才能向服务器发送请求并获得响应。
您可以在 MSDN 中找到相关信息