System.IO.DirectoryNotFoundException on server with the path from local machine - c#

I have created a web api with c# .net core 3.1 and I use a directory to save generated invoices there. the path to the directory on my local machine is C:\CU World\Backend\CU-API\CU-API\Generated Invoices\
On my local machine the api works fine. But on my linux server it does not work... I'm getting this error:
I do not understand why I am getting this error when I publish this to linux server with apache2 installed on it. Can somebody help me, and expain me how to fix it?

I could fix it by adding this to my Startp.cs
var fileProviderPath = Environment.GetEnvironmentVariable("FILE_PROVIDER_PATH");
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(fileProviderPath),
RequestPath = "/GeneratedInvoices"
});

Related

Can't write files on EC2 machine due to permissions

I am facing an issue where I am running .NET core app running on IIS and I need to read/write files locally on the machine but I am getting a runtime error when I try to access these files.
Access to the path 'C:\mydata\somedata'
is denied.
to avoid this issue I gave permissions to IIS_IUSRS user to read and write on the specified folder on the machine by connecting remotely to the machine and do that and everything is working okay right now.
The problem is that machine is running on aws beanstalk environment so every time that machine restarts a new instance is created without any permissions to IIS_IUSRS user and I need to go again and do it manually
my question, Is there anything I can do to not go through all that hassle of connecting to machine remotely and giving permissions manually?
I made a workaround in my Startup file by adding the following to app middlewares
app.UseFileServer(new FileServerOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, #"mydata/somedata")),
RequestPath = #"/SomeExampleRequestPath",
EnableDirectoryBrowsing = false
});
It allows you to read write files located locally on the machine without needing to give IIS read-write permissions

GitLab: Project Not Found: Runs Fine Locally, Doesn't Work Deployed

We have an app that updates a gitlab project and pushes/commits to master. When I run locally, the program runs fine. When I run on the application hosted server (not the gitlab server), I get a 404 "Project not found".
It's not the private access token, we just made a new one
I can sign in to gitlab on our app hosted server and find the project
I verified the account can push straight to master
There is no xdt transformation on the config files
I logged into the account on the app hosted server and hit the project via the same api url.
Here is the codified url:
RestRequest fileExists = new RestRequest(
$#"api/v4/projects/{project.id}/repository/files/{action.file_path.Replace("/", "%2F")}?ref=master&private_token={ConfigurationManager.AppSettings["JiraPrivateKey"]}",
Method.GET);
I'm almost thinking it's some sort of server setting, but I would think that I would get the 404 when I tried the api url in the browser.
After thinking about it, since I use the ConfigurationManager, I had to copy by .exe.config file to the server and not just the exe itself. After dragging the config and the exe over. It worked. :-(

UNC path is invalid when starting ASP.NET Core Application in IIS

I have a shared drive on my local network \hostname\shared\resource. I have mounted the drive programattically from within the Asp.net core web application in the startup.cs file.
app.UseStaticFiles();
app.UseFileServer(new FileServerOptions{
FileProvider = new
PhysicalFileProvider(#"\\TS3410D618\NickFlicks\Movies"),
RequestPath = new PathString("/Movies"),
EnableDirectoryBrowsing = false
});
This works perfectly when I run it with IIS express(debugging), however, when I deploy it to my local IIS on the same machine the application fails to start with the error:
Application startup exception: System.ArgumentException: The directory name
\\TS3410D618\NickFlicks\MoviePosters\ is invalid.
This is a valid UNC path and can be reached from everywhere I have tried on my windows 10 machine. As I mentioned everything is on the same machine except for the shared drive.
As a side note I can mount a virtual drive from within IIS sucessfully, so IIS can access the fileshare without any issues.
I'm not sure what I am doing wrong here, any help would be greatly appreciated.
I could never get this to work because I couldn't find a way to create an Active Directory with Windows 10 or to modify the user permissions for the UNC file share for the user used by IIS. Basically, I just installed Ubuntu server with Nginx as the reverse proxy and everything worked fine once I set up the permissions properly, which was very straight forward.

how to use asp.net core web api sqlite database in a host server

Im using Visual Studio Mac.
Im working on a asp.net core web api with sqlite database.
it works fine in localhost.
but doesn't work on host server. it gives 500 internal server error.
I published it from a windows visual studio as ftp.
I think my internal error is because of my sqlite configuration.
its:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite("Filename=./MyData.db"));
I think this configuration doesn't work in host and I have no idea about it.
I just published it.
please help me with it.
I'd suggest you to:
Instead of using relative path on filename config, try using the absolute path.
Note: If it works, I'd recommend you to use
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(String.Format("Filename={0}/MyData.db", AppDomain.CurrentDomain.BaseDirectory));
As you're using './MyData.db', I believe 'AppDomain.CurrentDomain.BaseDirectory' is going to be enough, other than that, you must use your correct file location.
[Solved]
Add this statement to the method you're calling.
try
{
//YOURCODE
}
catch (Exception e)
{
return StatusCode(500, $"An error has ocurred. Ex: e.InnerException.Message}"); }
Check the error message (no such table: MyTable)
Create the table.
Problem solved.
Best Regards

ASP.NET Core 1.1 runs fine locally but when publishing to Azure says "An error occurred while starting the application."

I've been developing an ASP.NET Core web app, based largely on the MVC template provided in Visual Studio 2017 RC2. It runs just fine in local debug mode, but when I try to publish it to an Azure hosted web app, I get this error:
An error occurred while starting the application.
.NET Core X86 v4.1.1.0 | Microsoft.AspNetCore.Hosting version
1.1.0-rtm-22752 | Microsoft Windows 6.2.9200
I've tried setting stdoutLogEnabled="true" in the web.config file, but it seems to have no effect, the error is the same.
Update:
With some help I managed to retrieve the log, and it says:
Application startup exception: System.TypeLoadException: Could not load type 'System.IO.File' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
at Microsoft.Extensions.DependencyModel.FileWrapper.OpenRead(String path)
at Microsoft.Extensions.DependencyModel.DependencyContextLoader.LoadEntryAssemblyContext(IDependencyContextReader reader)
at Microsoft.Extensions.DependencyModel.DependencyContextLoader.Load(Assembly assembly)
at Microsoft.Extensions.DependencyModel.DependencyContext.Load(Assembly assembly)
at Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(String entryPointAssemblyName)
at Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.GetApplicationPartManager(IServiceCollection services)
at Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection services)
at Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services)
at Bla.Api.Startup.ConfigureServices(IServiceCollection services) in C:\Users\user\Source\Workspaces\Bla\Bla.Api\src\Bla.Api\Startup.cs:line 73
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: D:\home\site\wwwroot
Now listening on: http://localhost:1264
Application started. Press Ctrl+C to shut down.
The line of code it refers to at line 73 is:
services.AddMvc();
Update:
My global.json file looks like this (where Bla.Api is the name of the project, and the file sits in the solution root folder).
{
"projects": [ "Bla.Api" ],
"sdk": {
"version": "1.1.0"
}
}
Since many different problems can cause this error page, I can strongly recommend the following in order to determine the root cause quickly and easily, without wrestling Azure (or any server/platform for that matter) to get logs.
You can enable extremely helpful developer friendly error messages at startup by setting the .UseSetting("detailedErrors", "true") and .CaptureStartupErrors(true) actions in your Program.cs file.
For ASP.NET Core 1.x
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseSetting("detailedErrors", "true")
.UseIISIntegration()
.UseStartup<Startup>()
.CaptureStartupErrors(true)
.Build();
host.Run();
}
(2018/07) Update for ASP.NET Core 2.1
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true")
.UseStartup<Startup>()
.Build();
}
These settings should be removed as soon as your troubleshooting is complete so as not to expose your application to malicious attacks.
Connect via an sftp client and delete everything in the site/wwwroot folder manually. Republish
I have had nothing but problems since I migrated an application I have hosted on Azure to .net core from MVC 4.
At one point a few weeks ago I was unable to get a project to run after a successful publish. I even tried twice to delete the entire App Service profile and recreate it with the same name. However when I appended a '2' to the App Service name (to create a never before used app service) publishing the exact same project with 0 changes worked perfectly. What exactly does a delete do if I can publish successfully to a new app service but not a deleted and recreated one? Remove Existing Files At Destination was checked in each publish, that didn't do anything either.
I had the same error today as pictured in the OP in my #2 site. It occurred after attempting to update a number of asp nuget packages and re-deploy. Really not wanting to have to move on to iteration myApp3 of my app service, I decided to use the FTP information provided in the azure overview page. I navigated to Site/wwwroot and deleted everything inside from the FTP client. I then published the application, and it worked. I can only conclude that the 'Delete' checkbox doesn't work properly.
Thanks everyone for your suggestions. The only thing that worked in the end though is deleting that Azure web app that I couldn't publish to, and creating a brand new one. I guess maybe some of the .dlls from the previous runtime environment were still hanging around or not being updated... Whatever it was, re-creating it worked. Hopefully I don't get this error again though, because you can't really do this kind of stuff in production.
Making changes to the global.json file seemed to have no effect.
Creating an entirely new API from a template didn't help either, the issue was with the Azure Web App itself, as everything was running fine locally.
Another very helpful tip was to add logging (and the "logs" file in the root) as per the other answer. That at least pointed me in the right direction. Also checking your runtime with dotnet --version.
Again thanks for everyone's help!
I've got the same problem. Just not deployed at Azure, I'm using my local machine as server and host it in IIS.
An error occurred while starting the application.
.NET Core X64 v4.1.1.0 | Microsoft.AspNetCore.Hosting version 1.1.1 | Microsoft Windows 10.0.14393 | Need help?
And this was solved by changing web.config.
First set stdoutLogEnabled = "true"
Then make sure stdoutLogFile=".\logs\stdout" /> this folder exists.
And then restart IIS, you can find the real problem in log file.
DELETE all existing dll from wwwroot/your_application_folder, then copy all of the publish output files&folders.
The problem occurs when the NUGETS update it self. If you don't clean the existing files under wwwroot/your_application_folder IIS gives the error above.
Clean and rebuild fixed everything.
Question is probably duplicated - please refer to ASP.NET Core hosting - 500 internal server error.
Quick answer:
You need to set: stdoutLogEnabled="true" and stdoutLogFile=".\logs\stdout". Also, you need to create logs folder manually.
In my case, it was because I was trying to publish user secrets for use with Fabook OAuth. I know that's a very situational specific answer, but OAuth seems pretty common these day. User Secrets, it turns out, are not meant to be published. Who knew.
So to test this I temporarily changed the following code in startup.cs. This data should be not hard coded as a part of best practice, as it would end up in clear text in source control.
Before
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"]
});
After
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = "0000000000000", // your value
AppSecret = "0000000000000000000000000000000" // your value
});
Then it worked.
In My case, that was because I was trying to get a some data in Startup, and dbcontext was not updated in production environment.
Changed my ConnectionString to Production and runned Update-Database, and problem solved.
In my case there was a directory named Resources that was missing in app directory.

Categories

Resources