in asp.net 5 is it possible to store and read custom files in approot instead of wwwroot? - asp.net-core

when you deploy an asp.net5/mvc6 app there is the wwwroot folder where web assets like css, js, images belong, and there is approot folder where packages and source code belong.
It seems that classes in the Microsoft.Framework.Configuration namespace for example must be able to read files from below approot since that is where config.json files would live.
What I want to know is, is it possible to store and read custom files of my own in approot? and if so how?
For example I'm not using Entity Framework so I need a place to put sql install and upgrade scripts and would prefer not to put them beneath wwwroot. I also have custom configuration files for things like navigation sitemap that I would rather not put below wwwroot if it is possible to put them elsewhere such as approot.
I know I can access files below wwwroot using IHostingEnvironment env.MapPath("~/somefileinwwwrootfoilder.json")
Is there a similar way to access files under approot?

The accepted answer is correct, but since a ASP.NET Core 1.0 release a few things have changed so I thought I'd write a new clear things up a bit.
What I did was create a folder in my project called AppData. You can call it anything you like.
Note: it's not in wwwroot because we want to keep this data private.
Next, you can use IHostingEnvironment to get access to the folder path. This interface can be injected as a dependency into some kind of helper service and what you end up with is something like this:
public class AppDataHelper
{
private readonly IHostingEnvironment _hostingEnvironment;
private const string _appDataFolder = "AppData";
public AppDataHelper(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public async Task<string> ReadAllTextAsync(string relativePath)
{
var path = Path.Combine(_hostingEnvironment.ContentRootPath, _appDataFolder, relativePath);
using (var reader = File.OpenText(path))
{
return await reader.ReadToEndAsync();
}
}
}
Additionally, to get things to deploy correctly I had to add the AppData folder to the publishOptions include list in project.json.
As mentioned in the comments, to deploy AppData folder correctly in ASP.NET MVC Core 2 (using *.csproj file, instead of project.json), syntax is as follows:
<ItemGroup>
<None Include="AppData\*" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>

Yes, it is possible. Just get the path to your app folder and the pass it to configuration or whoever else needs it:
public class Startup
{
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var wwwrootRoot = env.WebRootPath;
var appRoot = appEnv.ApplicationBasePath;

Related

How to get the virtual path of File from wwwroot folder of asp.net core app?

I want to get the virtual path to my index.html file which is present in wwwroot folder of my asp.net core web API. I have attached my picture of code which will explain the situation of this problem.
right now I am just using its full path which is not convenient method of using path like this so that is why I want to get virtual path of this file so that on any other server I will not face any problems.
Inject IHostingEnvironment in your controller and use its WebRootPath to access your files
using Microsoft.AspNetCore.Hosting;
//...
public class AccountController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public AccountController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
//...
string htmlFilePath = Path.Combine(_hostingEnvironment.WebRootPath, "EmailTemplate", "index.html");
//...
}

asp.net core appsettings.json include reference to anthor file

I am working on a C# ASP.NET Core 3.1 project, angular is the front end. I have a requirement to put some text (multiline) inside a text file and point to it in appsettings.json as below:
"MySettings": {
"Parameters": {
"instructionFile": "filename.txt",
},
}
I can read these in, but I don't know how to access the 'filename.txt', so as to 'System.IO.File.ReadAllText(filename.txt)', where should I put that filename.txt and what's the full path to it? my Startup has app.UseStaticFiles(), so I assume I should put it inside wwwroot/? but when I put it there, I tried ~/filename.txt, it didn't find it.
You can read the appsettings.json file using IConfiguration like
private IConfiguration _configuration;
string fileName = _configuration.GetValue<string>("MySettings:Parameters:instructionFile")
In order to read the content of the file:
// Load the souce file if the file location is within the project, if it's a url then get it via making http requrest
string _filePath = Path.Combine(Environment.CurrentDirectory, #""+ fileName +"");
string fileContent= File.ReadAllText(_filePath);
Thanks

How to specify the path to a VS extension DLL from an MSBuild <UsingTask> tag

I'm developing a Visual Studio extension. The extension's associated VS project template includes a call to a custom task in the extension's DLL:
<UsingTask TaskName="MyTask" AssemblyFile="path to MyDLL.dll" />
The extension will be installed in the usual place, through use of the VSIX installer.
My question is: Is there a good MSBuild property or macro that I can use to construct the path to the extension's DLL (i.e., MyDLL.dll)? I'm aware of $(DevEnvDir) and could extend that path when using the project and extension in Visual Studio 2015 (append \VendorName\ProductName\Version), but that doesn't seem to work in VS 2017, where the appended path uses a mangled name that can't be predicted ahead of time (or can it?). There's also the issue that the project/extension should work in the VS experimental instance, which does not appear to reflect $(DevEnvDir).
Is there any good way to do this with MSBuild properties, or will I need to look at alternatives like environment variables or the registry?
Is there any good way to do this with MSBuild properties, or will I need to look at alternatives like environment variables or the registry?
You can use environment variables or the registry to achieve it.
environment variables
you could use environment variables like this:
<UsingTask TaskName="MyTask" AssemblyFile="$(yourenvironmentvariablesname)MyDLL.dll" />
For more information, please refer to:
https://learn.microsoft.com/en-us/visualstudio/msbuild/how-to-use-environment-variables-in-a-build
registry
You could use registry like this:
<UsingTask TaskName="MyTask" AssemblyFile="$(Registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework#DbgManagedDebugger)MyDLL.dll" />
Note: please change related registry path as you want.
https://blogs.msdn.microsoft.com/msbuild/2007/05/04/new-registry-syntax-in-msbuild-v3-5/
The solution that made sense for me was to create a wizard and to set the path to the extension install location in the replacements dictionary and use the replacement in the template with the UsingTask.
public class ProjectLocationWizard : IWizard
{
public void BeforeOpeningFile(ProjectItem projectItem)
{
}
public void ProjectFinishedGenerating(Project project)
{
}
public void ProjectItemFinishedGenerating(ProjectItem projectItem)
{
}
public void RunFinished()
{
}
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
var wizardDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
replacementsDictionary.Add("$installlocation$", wizardDirectory);
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
}
<UsingTask AssemblyFile="$installlocation$\MyTask.dll" TaskName="MyTask" />
Although the wizard docs say to sign the wizard assembly, I did not, and it works fine without.

What is causing the error that swagger is already in the route collection for Web API 2?

I installed Swagger in my ASP.Net MVC Core project and it is documenting my API beautifully.
My co-worker asked me to install it in a full framework 4.6.1 project so I've done the following.
In Package Console Manager run:
Install-Package Swashbuckle
To get your Test Web API controller working:
1) Comment this out in the WebApi.config:
// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
Now this URL:
http://localhost:33515/api/Test
brings back XML:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
In Global.asax Register() I call:
SwaggerConfig.Register();
In AppStart.Swagger.Config Register() I put:
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1.0", "HRSA CHAFS");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{});
}
private static string GetXmlCommentsPath()
{
var path = String.Format(#"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
return path;
}
}
Now I get this error:
"A route named 'swagger_docsswagger/docs/{apiVersion}' is already in the route collection. Route names must be unique."
I've been stuck on this for hours.
How do you get rid of this?
This can happen when you re-name your .NET assembly. A DLL with the previous assembly name will be present in your bin folder. This causes the swagger error.
Delete your bin folder and re-build your solution.
This resolves the swagger error.
Swagger config uses pre-application start hook, so you don't need to call SwaggerConfig.Register() explicitly. Otherwise Register method is called twice.
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
in my case i added another project as refrence and that other project has swagger too.
i remove that refrence and move needed code to new project.
I solved the problem by deleting the SwaggerConfig.cs file from the App_Start folder as I had already created it manually.
Take a look at this link, here also has more useful information:
A route named 'DefaultApi' is already in the route collection error
In my experience the error occurs when you add reference to another project and that project is a service and it occurs on the SwaggerConfig of the referenced project. Removing project reference usually solve the problem, if you need to share classes I suggest you to create a specific project as Class Library and add its reference to both your services

How can you use multiple directories for static files in an aspnet core app?

By default, the wwwroot directory can host static files. However, in some scenarios, it might be ideal to have two directories for static files. (For example, having webpack dump a build into one gitignored directory, and keeping some image files, favicon and such in a not-gitignored directory). Technically, this could be achieved by having two folders within the wwwroot, but it might organizationally preferable to have these folders at the root level. Is there a way to configure an aspnet core app to use two separate directories for static files?
Just register UseStaticFiles twice:
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "static"))
});
Now files will be found from wwwroot and static folders.
Registering UseStaticFiles twice won't solve it for MapFallbackToFile
An alternative approach.
// Build the different providers you need
var webRootProvider =
new PhysicalFileProvider(builder.Environment.WebRootPath);
var newPathProvider =
new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, #"Other"));
// Create the Composite Provider
var compositeProvider =
new CompositeFileProvider(webRootProvider, newPathProvider);
// Replace the default provider with the new one
app.Environment.WebRootFileProvider = compositeProvider;
https://wildermuth.com/2022/04/25/multiple-directories-for-static-files-in-aspnetcore/