ASP.Net MVC Core: Javascript files in Areas along with Views (.cschtml)
Areas in MVC allow you to separate your web application into segments,
each with their own set of Controllers and Views, for better organization and
intuitive access via routing. Here
I want to manage my static java script files particular objects in areas i.e. I
want to place my CountryDetail.js and CountryGrid.js files in Areas/Setup/Country
Folder along with CountryDetail.cshtml and CountryGrid.cshtml.
As you know,
in .Net Core, as part of the OWIN pipeline, no static files are rendered by
default including those in the "wwwroot" folder. Where things used to
be handled in web.config, now everything goes through the OWIN pipeline. You
have to add the StaticFile Middleware which will allow those to be rendered.
The default implementation allows all files under "wwwroot" to be
rendered.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
}
Here is the
official Microsoft documentation: Working with StaticFiles in ASP.NET Core
The below
code will add StaticFiles Middleware to only allow javascript files to be
rendered from the "Areas" folder. You can add other files by adding
items to the Dictionary after this line {".js", "application/javascript" } with comma
separated.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
// Render only .js files in "Views" folder
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"Areas")),
RequestPath = new PathString("/Areas"),
ContentTypeProvider = new FileExtensionContentTypeProvider(
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{".js", "application/javascript" }
})
}
);
}
Thanks Manoj
ReplyDelete