【发布时间】:2018-03-02 12:42:32
【问题描述】:
我正在制作一个 ASP.NET Web 应用程序,我用它来编辑 Windows 服务的设置(一个 XML 文件)。 Windows 服务可以与 Web 应用程序在同一台服务器上运行,我已经让它完美运行,我遇到的问题是当 Windows 服务在不同的服务器上运行并且 Web 应用程序需要将 Xml 文件发送到Windows 服务。
我的目标是让 ASP.NET Web 应用程序将刚刚通过 Http 更新的 XML 文件发送到具有 HttpListener 的 Windows 服务。
到目前为止我所管理的:
ASP.NET 应用程序:
public string PushSettings(string serverName, string xmlFile)
{
var prefix = "http://" + serverName+ ":";
var portnumber = ConfigurationManager.AppSettings["PortNumber"];
var command = ConfigurationManager.AppSettings["PushSettingsCommand"];
var request = (HttpWebRequest)WebRequest.Create(prefix + portnumber + command);
var bytes = System.Text.Encoding.ASCII.GetBytes(xmlFile);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
var requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
try
{
var response = (HttpWebResponse)request.GetResponse();
return response.StatusCode.ToString();
}
catch (WebException ex)
{
Log.Info("WebException thrown while trying to connect to httplistener. Exception message: " + ex.Message + " The following request was attempted: " + prefix + portnumber + command);
throw new WebException("WebException thrown while trying to connect to httplistener. Exception message: " + ex.Message + " The following request was attempted: " + prefix + portnumber + command);
}
}
(string xmlFile是整个XML文件的字符串)
Windows 服务:
public void RunHttpListener()
{
var listener = new HttpListener();
try
{
listener.Prefixes.Add(_Prefix);
listener.Start();
var context = listener.GetContext();
var request = context.Request;
var ipAdress = context.Request.RemoteEndPoint?.ToString();
if(_Prefix.Contains("PushSettings"))
{
SaveFile(context.Request.ContentEncoding, getSettings.GetBoundary(context.Request.ContentType), context.Request.InputStream);
}
var response = context.Response;
const HttpStatusCode responseString = HttpStatusCode.OK;
var buffer = Encoding.UTF8.GetBytes(responseString.ToString());
response.ContentLength64 = buffer.Length;
var output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
listener.Stop();
}
catch (Exception ex)
{
Log.Info(ex.Message);
if (listener.IsListening)
{
listener.Stop();
}
}
}
(_Prefix 例如:{serverName}/PushSettings)
GetBoundary() 和 SaveFile() 是我在 Stack Overflow 线程上找到的代码:Httplistener and file upload,它会引发异常,因为 len == 0 在第三次循环通过第一个 while (真的) { }。这是该线程的代码:
public String GetBoundary(String ctype)
{
return "--" + ctype.Split(';')[1].Split('=')[1];
}
public void SaveFile(Encoding enc, String boundary, Stream input)
{
var boundaryBytes = enc.GetBytes(boundary);
var boundaryLen = boundaryBytes.Length;
using (var output = new FileStream("Settings.xml", FileMode.Create, FileAccess.Write))
{
var buffer = new Byte[1024];
var len = input.Read(buffer, 0, 1024);
var startPos = -1;
// Find start boundary
while (true)
{
if (len == 0)
{
throw new Exception("Start Boundaray Not Found");
}
startPos = IndexOf(buffer, len, boundaryBytes);
if (startPos >= 0)
{
break;
}
else
{
Array.Copy(buffer, len - boundaryLen, buffer, 0, boundaryLen);
len = input.Read(buffer, boundaryLen, 1024 - boundaryLen);
}
}
// Skip four lines (Boundary, Content-Disposition, Content-Type, and a blank)
for (var i = 0; i < 4; i++)
{
while (true)
{
if (len == 0)
{
throw new Exception("Preamble not Found.");
}
startPos = Array.IndexOf(buffer, enc.GetBytes("\n")[0], startPos);
if (startPos >= 0)
{
startPos++;
break;
}
else
{
len = input.Read(buffer, 0, 1024);
}
}
}
Array.Copy(buffer, startPos, buffer, 0, len - startPos);
len = len - startPos;
while (true)
{
var endPos = IndexOf(buffer, len, boundaryBytes);
if (endPos >= 0)
{
if (endPos > 0) output.Write(buffer, 0, endPos - 2);
break;
}
else if (len <= boundaryLen)
{
throw new Exception("End Boundaray Not Found");
}
else
{
output.Write(buffer, 0, len - boundaryLen);
Array.Copy(buffer, len - boundaryLen, buffer, 0, boundaryLen);
len = input.Read(buffer, boundaryLen, 1024 - boundaryLen) + boundaryLen;
}
}
}
}
public Int32 IndexOf(Byte[] buffer, Int32 len, Byte[] boundaryBytes)
{
for (var i = 0; i <= len - boundaryBytes.Length; i++)
{
var match = true;
for (Int32 j = 0; j < boundaryBytes.Length && match; j++)
{
match = buffer[i + j] == boundaryBytes[j];
}
if (match)
{
return i;
}
}
return -1;
}
这是 XML 文件外观的(缩短的)示例
<?xml version="1.0" encoding="UTF-8"?>
<MonitorSettings>
<Interval>30000</Interval>
<QueuCheck>False</QueuCheck>
<MailAlert>False</MailAlert>
<WindowsServices>mongodb</WindowsServices>
</MonitorSettings>
到目前为止,我的 Windows 服务代码能够接收来自 Web 应用程序的请求,但是由于 len == 0 时引发的异常,它没有保存 XML 文件。我做错了什么吗?有没有更好的方法来做事?有什么好的 StackOverflow 线程可以提供帮助吗?
编辑 更准确地说,异常是在函数 SaveFile() 中引发的,第三次在 while(true){ } 中循环:
if (len == 0)
{
throw new Exception("Start Boundaray Not Found");
}
【问题讨论】:
-
能否补充一下引发异常的时间和地点?可能是日志,但最重要的是代码中的行和变量?
-
编辑了问题以包括抛出异常的位置。
标签: c# httprequest httplistener