-
Notifications
You must be signed in to change notification settings - Fork 48
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
Comments
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. |
Hey, thanks for the link it was very helpful. 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();
|
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.
The text was updated successfully, but these errors were encountered: