0

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 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

"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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.