tomkuijsten / restup

Webserver for universal windows platform (UWP) apps
MIT License
114 stars 48 forks source link

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

Closed Bjego closed 6 years ago

Bjego commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

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();