Last active
August 29, 2015 14:16
-
-
Save jesperbjensen/453015d224106968a4b0 to your computer and use it in GitHub Desktop.
A snippet that shows two ways to read files using ASP.NET 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using File.ReadAllText | |
public async Task MyMiddleWare(HttpContext context, IApplicationEnvironment env) | |
{ | |
var html = File.ReadAllText(env.ApplicationBasePath + "/Views/index.html"); | |
await context.Response.WriteAsync(html); | |
} | |
// Using FileProvider | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddTransient<IFileProvider>(s=>new PhysicalFileProvider(s.GetRequiredService<IApplicationEnvironment>().ApplicationBasePath)); | |
} | |
public async Task MyMiddleWare(HttpContext context, IFileProvider fileProvider) | |
{ | |
var html = ReadAllFromStream(fileProvider.GetFileInfo("Views/index.html").CreateReadStream()); | |
await context.Response.WriteAsync(html); | |
} | |
private string ReadAllFromStream(Stream stream) | |
{ | |
using (var reader = new StreamReader(stream)) | |
{ | |
return reader.ReadToEnd(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment