2009-07-30 18 views

回答

2

如果该文件是足够小你可以很容易地适应它在内存中(你会希望它是,如果你通过邮递),那么你可以简单地做到以下几点:

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”]

0

我很困惑;你说你想要它作为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

0

如果您的webmethod使用HttpContext.Current.Request.Headers["errorLog"],那么您的客户端应用程序在执行请求时需要发送此自定义http标头。请注意,http标头并不意味着发送大量数据。

在您的客户端应用程序,你可以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; 
} 
相关问题