I want to know if its possible to send a file to a generic handler in c#, and generate some kind of response. For example: post a .txt file to the handler. The handler check if a textfile is submitted and then converts it to json as response. Hope you get the idea. Thanks
2 Answers
You can write your handler like this:
public class FileUploadHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
HttpResponse response = context.Response;
foreach (string file in context.Request.Files)
{
HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
if (hpf.ContentLength == 0)
continue;
//DO SOMETHING WITH FILE.
}
//RETURN ANY RESPONSE USING response OBJECT
}
public bool IsReusable
{
get
{
return false;
}
}
}
for Request.Files stuff read Scott Hanselman's this post
Comments
It looks like you're talking about creating a web service. This tutorial might be a good starting point: http://www.dotnetperls.com/ashx
The basic idea is that you'll create your handler function within a .ashx file, pass it your file information (textfile) via an HTTP POST request, and then write whatever JSON you want to the response object.
2 Comments
Johan
"pass it your file information (textfile) via an HTTP POST request". So i upload the file to the server -> send data from file to handler via a HttpWebRequest -> handler generates json?
Mirthquakes
Yep, I think we're on the same page. When you've uploaded the file to the server (your target being yourservice.ashx) you can access the file as a System.Web.HttpPostedFile object. It's stored in the 'Files' collection attribute of your HttpWebRequest object. When you're ready to write your response, put your desired JSON in the Response.Write() function.