Reputation: 3084
I have an c# ashx handler that detects files attached. It works fine.
However, I am relying on third party company to write software to send files to handler (long story). I need to test that my handler works, time difference between us and 3rd party company is becoming a nightmare.
The scenario is 3rd party software sends files every 30 seconds to handler and I need to test this works and without sounding stupid I thought I ask stackoverflow :)
I just want to test my ashx handler using test unit or whatever but no idea where to start. Typing in "handler.ashx?filename=12345.csv" is helpful but no actual file attached!
Any suggestions would be great.
Upvotes: 2
Views: 5050
Reputation: 24413
From what I understand, you have an ashx handler that you can upload files to and you want to test it.
I have attached a sample test that assumes an ashx handler that uses a POST request for file attachments.
[TestMethod]
public void TestCallUploadHandler()
{
const string FILE_PATH = "C:\\foo.txt";
const string FILE_NAME = "foo.txt";
string UPLOADER_URI =
string.Format("http://www.foobar.com/handler.ashx?filename={0}", FILE_NAME);
using (var stream = File.OpenRead(FILE_PATH))
{
var httpRequest = WebRequest.Create(UPLOADER_URI) as HttpWebRequest;
httpRequest.Method = "POST";
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(httpRequest.GetRequestStream());
var httpResponse = httpRequest.GetResponse();
StreamReader reader = new StreamReader(httpResponse.GetResponseStream());
var responseString = reader.ReadToEnd();
//Check the responsestring and see if all is ok
}
}
Basically what you are doing is creating a WebRequest for POST and attaching the filestream to its request and filename to its query string.
Upvotes: 4
Reputation: 3084
To answer my question and many thanks to @parapura:
[TestMethod]
public void TestCallUploadHandler()
{
const string FILE_PATH = "C:\\foo.txt";
const string FILE_NAME = "foo.txt";
string UPLOADER_URI = string.Format("http://www.foobar.com/handler.ashx?filename={0}", FILE_NAME);
using (var stream = File.OpenRead(FILE_PATH))
{
var httpRequest = WebRequest.Create(UPLOADER_URI) as HttpWebRequest;
httpRequest.Method = "POST";
NetworkCredential networkCredential = new NetworkCredential("username", "pwd");
httpRequest.Credentials = networkCredential;
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(httpRequest.GetRequestStream());
byte[] authBytes = Encoding.UTF8.GetBytes("username:pwd".ToCharArray());
httpRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
var httpResponse = httpRequest.GetResponse();
StreamReader reader = new StreamReader(httpResponse.GetResponseStream());
var responseString = reader.ReadToEnd();
//Check the responsestring and see if all is ok
}
}
Upvotes: 0