将数据从文本文件(由桌面客户端读取)发布到基于ASP .NET的服务器
题
我正在开发一个客户端 - 服务器应用程序 - 服务器是一个ASP .NET Web应用程序。
客户端(桌面应用程序)需要将文本文件中包含的数据发送到我的asp .net web应用程序。 数据大约为100 KB,采用多行文本形式。
将此数据发布到服务器的最佳方法是什么,因为我需要每10分钟左右执行一次这样的操作?
解决方案
如果文件足够小,您可以轻松地将其放入内存中(如果您通过POST发送它,则可能需要它),那么您只需执行以下操作:
string textFileContents = System.IO.File.ReadAllText( @"C:\MyFolder\MyFile.txt" );
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://www.myserver.com/myurl.aspx" );
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "fileContents=" + System.Web.HttpUtility.UrlEncode( textFileContents );
byte[] data = encoding.GetBytes( postData );
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write( data, 0, data.Length );
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// do something with the response if required
就阅读文本服务器端而言,您只需使用Page.Request.Form [" fileContents" ]
其他提示
我很困惑;你说你想把它作为POST参数,但是你从头文件中读出来了吗?那将是典型的帖子字段的表单,或者只是原始数据的请求体......
发送表单字段:
NameValueCollection fields = new NameValueCollection();
fields.Add("name1","some text");
fields.Add("name2","some more text");
using (var client = new WebClient())
{
byte[] resp = client.UploadValues(address, fields);
// use Encoding to get resp as a string if needed
}
要发送原始文件(不是表单;只是文本本身),请使用 UploadFile
;对于标题,请使用 .Headers.Add
。
如果您的webmethod使用 HttpContext.Current.Request.Headers [" errorLog"]
,那么您的客户端应用程序需要在执行请求时发送此自定义http标头。请注意,http标头并不意味着发送大数据。
在您的客户端应用程序中,您可以向Web服务中添加Web引用,并使用生成的代理类覆盖 GetWebRequest 并添加自定义http标头:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
var req = (HttpWebRequest)base.GetWebRequest(uri);
var value File.ReadAllText("path_to_your_file");
req.Headers.Add("errorLog", value);
return (WebRequest)req;
}
不隶属于 StackOverflow