ارتقاء به ASP.NET Core 1.0 - قسمت 4 - فعال سازی پردازش فایلهای استاتیک
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۴/۱۸ ۱۳:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
"dependencies": {
// same as before
"Microsoft.AspNetCore.StaticFiles": "1.0.0"
}, public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
//app.UseWelcomePage();
app.Run(async context =>
{
await context.Response.WriteAsync("Hello DNT!");
});
}
} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello World</title> </head> <body> Hello World! </body> </html>
public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles();
// Serve my app-specific default file, if present.
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mydefault.html");
app.UseDefaultFiles(options); public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
app.UseDefaultFiles();
○ wwwroot § css § images § ... ○ MyStaticFiles § test.png
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(root: Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles")
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new PhysicalFileProvider(root: Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
}); Unable to resolve service for type 'System.Text.Encodings.Web.HtmlEncoder' while attempting to activate 'Microsoft.AspNetCore.StaticFiles.DirectoryBrowserMiddleware'.
public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
}
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(root: Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
}); using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
namespace Core1RtmEmptyTest
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
}
public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles();
app.UseStaticFiles(); // For the wwwroot folder
// For the files outside of the wwwroot
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(root: Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles")
});
// For DirectoryBrowser
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(root: Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
FileProvider = new PhysicalFileProvider(root: Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
});
//app.UseWelcomePage();
app.Run(async context =>
{
await context.Response.WriteAsync("Hello DNT!");
});
}
}
} app.UseFileServer();
app.UseFileServer(enableDirectoryBrowsing: true);
app.UseFileServer(new FileServerOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles"),
EnableDirectoryBrowsing = false
}); // Set up custom content types -associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".xyz"] = "text/html";
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
}) ; // For the wwwroot folder
public class XyzContentTypeProvider : FileExtensionContentTypeProvider
{
public XyzContentTypeProvider()
{
this.Mappings.Add(".xyz", "text/html");
}
} app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = new XyzContentTypeProvider()
}) ; // For the wwwroot folder app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "image/png"
});
<img src='@Url.Action("DownloadFile", "ImageHandler", new {Area = "", id = item.BaseFileGuids, imgSize = ImageHandlerController.ImgSize.M})' alt=""/>
public IActionResult DownloadFile([FromRoute]string id, [FromQuery] ImgSize imgSize)
{
var result = _baseFileService.GetFileNameAndFileNameOnDsAndFileType(id);
if (result == null) return View("Error");
var fileName = result.Item1;
string userAgent = Request.Headers["User-Agent"];
if (IsInternetExplorer(userAgent))
{
var htencode = HtmlEncoder.Create();
var attachment = string.Format("attachment; filename=\"{0}\"", htencode.Encode(fileName));
_httpContext.HttpContext.Response.Headers.Add("Content-Disposition", attachment);
}
var rootPath = Path.Combine(_hostingEnvironment.WebRootPath, _settingsAppPathConfig.Value.ServerImagesRootPath);
var filepath = Path.Combine(rootPath, imgSize.ToString().ToLower(), result.Item2);
if (!System.IO.File.Exists(filepath))
{
const string notFoundImage = "notFound.jpg";
var notFoundpath = Path.Combine(rootPath , notFoundImage);
string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(notFoundImage, out contentType);
return File(notFoundpath, contentType, notFoundImage);
}
string contentTypebase;
new FileExtensionContentTypeProvider().TryGetContentType(result.Item3, out contentTypebase);
return File(filepath, contentTypebase, fileName);
} private IFileProvider GetFileProvider(VirtualFileResult result)
{
if (result.FileProvider != null)
{
return result.FileProvider;
}
result.FileProvider = _hostingEnvironment.WebRootFileProvider;
return result.FileProvider;
} return File("~/foo.js","text/javascript") [AllowAnonymous]
[ResponseCache(VaryByHeader = "id;imgSize", Duration = 30, Location = ResponseCacheLocation.Client, NoStore = true)]
public IActionResult DownloadFile([FromRoute]string id, [FromQuery] ImgSize imgSize)
{
//Tuple<string, string, string>(queryResult.FileName, queryResult.FileOnDs,queryResult.FileContentType)
var result = _baseFileService.GetFileNameAndFileNameOnDsAndFileType(id);
if (result == null) return View("Error");
var fileName = result.Item1;
string userAgent = Request.Headers["User-Agent"];
if (IsInternetExplorer(userAgent))
{
var htencode = HtmlEncoder.Create();
var attachment = string.Format("attachment; filename=\"{0}\"", htencode.Encode(fileName));
_httpContext.HttpContext.Response.Headers.Add("Content-Disposition", attachment);
}
var rootPath = Path.Combine(_hostingEnvironment.WebRootPath, _settingsAppPathConfig.Value.ServerImagesRootPath);
var filepath = Path.Combine(rootPath, imgSize.ToString().ToLower(), result.Item2);
var filefinalpath = "~/" + _settingsAppPathConfig.Value.ServerImagesRootPath + "/" + imgSize.ToString().ToLower() + "/" + result.Item2;
if (!System.IO.File.Exists(filepath))
{
const string notFoundImage = "notFound.jpg";
var notFoundpath = "~/" + _settingsAppPathConfig.Value.ServerImagesRootPath + "/"+ notFoundImage;
string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(notFoundImage, out contentType);
return File(notFoundpath, contentType, notFoundImage);
}
string contentTypebase;
new FileExtensionContentTypeProvider().TryGetContentType(result.Item3, out contentTypebase);
return File(filefinalpath, contentTypebase, fileName);
} <Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
</ItemGroup>
</Project> Install-Package Mime
// Guess mime type of file(overloaded method takes byte array or stream as arg.)
MimeGuesser.GuessMimeType("path/to/file"); //=> image/jpeg