Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Please provide an example how to write a custom Routehandler to return e.g. a csv file #133

Closed
Bjego opened this issue Dec 30, 2017 · 2 comments

Comments

@Bjego
Copy link

Bjego commented Dec 30, 2017

Hey guys,
could you please provide a sample how to write and use such a Routehandler (#129 )?
I try to return a csv file, but in the outcome \n\r are encoded as a string and no more as a new line.

        [UriFormat("/csv")]
        public IGetResponse Get()
        {

            IReadOnlyDictionary<string, string> header = new Dictionary<string, string>
                    {
                        {"Content-Type", "text/csv; charset=utf-8"},
                        {"Content-Disposition", "attachment;filename=log.csv"}
                    };
            var csv = CsvWriter.GetLogFile().Result;
            return new GetResponse(GetResponse.ResponseStatus.OK, header,  csv);
        }

@Jark
Copy link
Collaborator

Jark commented Jan 1, 2018

Hey @Bjego,

That is correct, you're using the RestRouteHandler and it always expects you to return the result of a REST action as an object, and that object will then either be encoded as json or xml, depending on what the client requests.

If you're looking to return csv files from the file system you could try using the static file handler (https://github.com/tomkuijsten/restup/wiki/StaticFiles-route-handler).

The StaticFileRouteHandler class (https://github.com/tomkuijsten/restup/blob/master/src/WebServer/File/StaticFileRouteHandler.cs) is also an example of a custom route handler so you should be able to figure it out by looking at the source.

Hope this helps.

@Bjego
Copy link
Author

Bjego commented Jan 28, 2018

Hey, thanks for the link it was very helpful.
I implemented it within 15 minutes. Now I can download my csv file by get from http://ipaddress:8888/csv .
Thanks a lot & here is the code for the handler:
Handler

public class CsvFileHandler : IRouteHandler
    {

        public async Task<HttpServerResponse> HandleRequest(IHttpServerRequest request)
        {
            if (request.Method != HttpMethod.GET)
            {
                return GetResponse(HttpResponseStatus.MethodNotAllowed, Encoding.UTF8.GetBytes("Only GET is allowed"));
            }
            try
            {
                var csv = await CsvWriter.GetLogFile();
                //csv is now the csvfile-content as normal string
                return GetResponse(HttpResponseStatus.OK, Encoding.UTF8.GetBytes(csv), "text/csv; charset=utf-8", $"log_{DateTime.Now.ToString("yyyy.MM.dd")}");
            }
            catch (FileNotFoundException)
            {
                return GetResponse(HttpResponseStatus.NotFound, Encoding.UTF8.GetBytes("Csv File not found"));
            }
        }

        private static HttpServerResponse GetResponse(HttpResponseStatus status, byte[] message) =>
             GetResponse(status, message, "text/plain", string.Empty);

        private static HttpServerResponse GetResponse(HttpResponseStatus status, byte[] message, string type, string fileName)
        {
            var respnse = HttpServerResponse.Create(new Version(1, 1), status);
            respnse.Content = message;
            respnse.ContentType = type;
            respnse.ContentCharset = "utf-8";
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                respnse.AddHeader("Content-Disposition", $"attachment;filename={fileName}.csv");
            }
            return respnse;
        }
    }

Registration:

var configuration = new HttpServerConfiguration()
              .ListenOnPort(8888)
              .RegisterRoute("csv", new CsvFileHandler())
              .EnableCors();

            var httpServer = new HttpServer(configuration);
            await httpServer.StartServerAsync();

@Bjego Bjego closed this as completed Jan 28, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants