HttpListener发布表单数据
本文关键字:表单 数据 布表单 HttpListener | 更新日期: 2023-09-27 18:27:38
我正在根据这个链接中的代码编写一个Web服务器。我正试图从表单中获取POST数据,但我我在获取这些数据时遇到了问题。该Web服务器是自托管的。它基本上是一个控制面板,我可以在其中添加和编辑这些设备,称为堆栈灯。这是我的WebServer.运行方法:
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("StackLight Web Server is running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
// set the content type
ctx.Response.Headers[HttpResponseHeader.ContentType] = SetContentType(ctx.Request.RawUrl);
WebServerRequestData data = _responderMethod(ctx.Request);
string post = "";
if(ctx.Request.HttpMethod == "POST")
{
using(System.IO.StreamReader reader = new StreamReader(ctx.Request.InputStream, ctx.Request.ContentEncoding))
{
post = reader.ReadToEnd();
}
}
if(data.ContentType.Contains("text") || data.ContentType.Equals("application/json"))
{
// serve text/html,css,js & application/json files as UTF8
// images don't need to be served as UTF8, they don't have encodings
char[] chars = new char[data.Content.Length / sizeof(char)];
System.Buffer.BlockCopy(data.Content, 0, chars, 0, data.Content.Length);
string res = new string(chars);
data.Content = Encoding.UTF8.GetBytes(res);
}
// this writes the html out from the byte array
ctx.Response.ContentLength64 = data.Content.Length;
ctx.Response.OutputStream.Write(data.Content, 0, data.Content.Length);
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
finally
{
ctx.Response.OutputStream.Close();
ctx.Response.Close();
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
});
}
我正在使用一个名为WebServerRequestData的类来获取我的页面、css、javascript和图像,以便为它们提供服务器。这个类看起来是这样的:
public class WebServerRequestData
{
// Raw URL from the request object
public string RawUrl { get; set; }
// Content Type of the file
public string ContentType { get; set; }
// A byte array containing the content you need to serve
public byte[] Content { get; set; }
public WebServerRequestData(string data, string contentType, string rawUrl)
{
this.ContentType = contentType;
this.RawUrl = rawUrl;
byte[] bytes = new byte[data.Length * sizeof(char)];
System.Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);
this.Content = bytes;
}
public WebServerRequestData(byte[] data, string contentType, string rawUrl)
{
this.ContentType = contentType;
this.RawUrl = rawUrl;
this.Content = data;
}
}
这是我的表格:
public static string EditStackLightPage(HttpListenerRequest request)
{
// PageHeadContent writes the <html><head>...</head> stuf
string stackLightPage = PageHeadContent();
// start of the main container
stackLightPage += ContainerDivStart;
string[] req = request.RawUrl.Split('/');
StackLightDevice stackLight = Program.StackLights.First(x => x.Name == req[2]);
stackLightPage += string.Format("<form action='/edit/{0}/update' method='post' enctype='multipart/form-data'>", stackLight.Name);
stackLightPage += string.Format("Stack Light<input type='text' id='inputName' value='{0}'>", stackLight.Name);
stackLightPage += string.Format("IP Address<input type='text' id='inputIp' value='{0}'>", stackLight.Ip);
stackLightPage += string.Format("Port Number<input type='text' id='inputPort' value='{0}'>", stackLight.Port);
stackLightPage += "<button type='submit'>Update</button>";
stackLightPage += "</form>";
// end of the main container
stackLightPage += ContainerDivEnd;
stackLightPage += PageFooterContent();
return stackLightPage;
}
它只有3个字段:name,ip&写入某些安全指示灯的自定义类的端口。它是从另一个类中的SendResponse方法调用的。
private static WebServerRequestData SendResponse(HttpListenerRequest request)
这是调用我的表单的片段,编辑url的示例是localhost:8080/edit/stackLight-Name
,更新将是localhost:8080/edit/stackLight-Name/update
。这是检查rawurl是否包含以下路由的代码:
if(request.RawUrl.Contains("edit"))
{
if (request.RawUrl.Contains("update"))
{
// get form data from the edit page and return to the edit
_resultString = WebServerHtmlContent.EditStackLightPage(request);
_data = new WebServerRequestData(_resultString, "text/html", request.RawUrl);
return _data;
}
_resultString = WebServerHtmlContent.EditStackLightPage(request);
_data = new WebServerRequestData(_resultString, "text/html", request.RawUrl);
return _data;
}
这是我处理请求的地方。它有一些基于HttpListenerRequest对象RawUrl属性的if语句。我正在尝试获取我的表单数据。在章节中:
if(ctx.Request.HttpMethod == "POST")
{
using(System.IO.StreamReader reader = new StreamReader(ctx.Request.InputStream, ctx.Request.ContentEncoding))
{
post = reader.ReadToEnd();
}
}
我可以获得InputStream,但无法获得表单数据。这是我得到的数据:"------WebKitFormBoundaryAGo7VbCZ2YC79zci--'r'n"
输入流中不应该包含我的表单数据吗?
我没有看到InputStream中表单字段中的任何数据。我尝试过使用application/x-www-form-urlencoded
,但它从ctx返回了一个null InputStream。要求(ctx是我的HttpListenerContext对象)。
我读过关于使用multipartform和application/x-www-form-urlencoded的文章,并尝试过这两种方法。
到目前为止,多部分表单为我提供了数据(尽管它不是表单数据),而另一部分则没有。
我想我的表格数据即将显示出来,我只是被困在了这一点上。我不知道该怎么办。
此外,现在我正在读这篇关于stackoverflow 的类似文章
编辑:在阅读了该链接后,我将web服务器的运行方法更改为:
try
{
// set the content type
WebServerRequestData data = _responderMethod(ctx.Request);
string post = "";
if(ctx.Request.HttpMethod == "POST")
{
data.ContentType = ctx.Request.ContentType;
post = GetRequestPostData(ctx.Request);
}
ctx.Response.ContentLength64 = data.OutputBuffer.Length;
ctx.Response.OutputStream.Write(data.OutputBuffer, 0, data.OutputBuffer.Length);
}
这是GetRequestPostData()方法:
private static string GetRequestPostData(HttpListenerRequest request)
{
if (!request.HasEntityBody)
return null;
using(System.IO.Stream body = request.InputStream)
{
using(System.IO.StreamReader reader = new StreamReader(body, request.ContentEncoding))
{
return reader.ReadToEnd();
}
}
}
我仍然只是得到"------WebKitFormBoundaryjiSulPEnvWX7MIeq--'r'n"
我想明白了,我忘了在表单字段中添加名称。
public static string EditStackLightPage(HttpListenerRequest request)
{
// PageHeadContent writes the <html><head>...</head> stuf
string stackLightPage = PageHeadContent();
// start of the main container
stackLightPage += ContainerDivStart;
string[] req = request.RawUrl.Split('/');
StackLightDevice stackLight = Program.StackLights.First(x => x.Name == req[2]);
stackLightPage += string.Format("<div class='col-md-8'><form action='/edit/{0}/update' class='form-horizontal' method='post' enctype='multipart/form-data'>", stackLight.Name);
stackLightPage += string.Format("<fieldset disabled><div class='form-group'><label for='inputName' class='control-label col-xs-4'>Stack Light</label><div class='col-xs-8'><input type='text' class='form-control' id='inputName' name='inputName' value='{0}'></div></div></fieldset>", stackLight.Name);
stackLightPage += string.Format("<div class='form-group'><label for='inputIp' class='control-label col-xs-4'>IP Address</label><div class='col-xs-8'><input type='text' class='form-control' id='inputIp' name='inputIp' value='{0}'></div></div>", stackLight.Ip);
stackLightPage += string.Format("<div class='form-group'><label for='inputPort' class='control-label col-xs-4'>Port Number</label><div class='col-xs-8'><input type='text' class='form-control' id='inputPort' name='inputPort' value='{0}'></div></div>", stackLight.Port);
stackLightPage += "<div class='form-group'><div class='col-xs-offset-4 col-xs-8'><button type='submit' class='btn btn-inverse'>Update</button></div></div>";
stackLightPage += "</form></div>";
// end of the main container
stackLightPage += ContainerDivEnd;
stackLightPage += PageFooterContent();
return stackLightPage;
}