.NET - properly deploy and publish [duplicate] - c#

I'm deploying a asp.net core 2.0 website to IIS 10.
I've made sure that my app is using the correct configuration for ISS in the program.settings file.
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
And in my startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<IISOptions>(options =>
{
});
services.AddMvc();
}
Yet when I run dotnet website.dll from the command line I get the below error message shown in the command line window:
An assembly specified in the application dependencies manifest
(website.deps.json) was not found:
package: 'Microsoft.AspNetCore.Antiforgery', version: '2.0.1'
path: 'lib/netstandard2.0/Microsoft.AspNetCore.Antiforgery.dll' This assembly was expected to be in the local runtime store as the
application was published using the following target manifest files:
aspnetcore-store-2.0.3.xml
Based off the error message, i'm guessing Microsoft.AspNetCore.Antiforgery isn't being bundled when I publish since I do not receive this error when debugging.
How can I ensure that my app can find Microsoft.AspNetCore.Antiforgery when published to a live environment?
EDIT: This is a basic .net core website. No changes have been made to the standard project at this time apart from the above changes for deployment with IIS.
When I run the project from IIS instead of the command line I get a 502.5 error message.

I was able to fix this issue by updating the .net core runtime on the server to v2.0.3.
This issue occurs if
You have an existing server running v2.0.0 of the .net core runtime.
You create an app targeting v2.0.3 of the SDK
You publish the v2.0.3 app to a server running v2.0.0
The issue can be resolved by installing v2.0.3 of the runtime on the server. You can download the runtime from the microsoft site here https://www.microsoft.com/net/download/windows

If you are actually using this library, make sure that your *.csproj file has the corresponding explicit reference:
<PackageReference Include="Microsoft.AspNetCore.Antiforgery" Version="..." />
Then, play with the PublishWithAspNetCoreTargetManifest property to resolve the aforementioned issue with a mismatched manifest.
Check out the following threads to learn more about possible issues while its deployment:
An assembly specified in the application dependencies manifest (RhWeb.deps.json) was not found
published application is missing assembly (missing runtime store associated ...) [2.0.0-preview2-005905]
HTTP Error 502.5 - Microsoft.AspNetCore.Antiforgery.dll

I had this issue - simple workaround, actually install the NuGet package (I wasn't using it).
Microsoft.AspNetCore.Antiforgery
Published, deployed - fixed the issue.
In another case, when I published the project, a lot of the dlls weren't being placed in the publish folder - including Antiforgery. The below appears to force publishing to add all the required dlls.
Edit your projectname.json file to ensure PropertyGroup contains PublishWithAspNetCoreTargetManifest = false:
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
</PropertyGroup>
Interested to know why the above works?!

This also problem happens if Antiforgery is called but Antiforgery is not installed.
Can be fixed by installing Microsoft.AspNetCore.Antiforgery by Nuget package manager.

I fixed this issue on my inhouse windowsserver with this solution
* go to netcore https://github.com/dotnet/core/tree/master/release-notes
* go to the lastest version of the core runtime 2.?
* download DotNetCore.2.0.6-WindowsHosting.exe in my case
https://github.com/dotnet/core/blob/master/release-notes/download-archives/2.0.6-download.md#net-core-runtime-only-installation
Install this on server and the error was solved for me. Hope this helps anyone.

Got this error after updating Microsoft.AspNetCore.All from v2.0.7 to v2.0.8 (latest at the time) and then publishing to a server that was running .NET Core Runtime v2.0.7 (latest at the time).
Downgraded Microsoft.AspNetCore.All back down to v2.0.7, re-published, and everything works.

If you publish the app as a self-contained ASP.NET Core 2.2 apps as per the linked screenshot (I don't have enough rep for inline image), it will fix this issue.
Self contained:
This can be set when editing your publish settings.

If this issue is related to your Razor mail template, you can add "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation". When I add, the problem is solved.

Related

Azure Pipelines unable to find .Net framework version 4.0

My solution uses the latest version of .net which is 4.8. However, I see the following error message that complaints about a version 4.0 in Azure Pipelines. Can someone let me know how I could resolve this please ?
The error message indicates I need to install 4.0 but I don't think that's the solution. I also opened up the file Microsoft.Common.CurrentVersion.targets and line 1221 has the following. However, I know it is not advisable to edit this file.
<!-- By default if there is no root path set then the task will assume it is Program Files\Reference Assemblies\Microsoft\Framework-->
<GetReferenceAssemblyPaths
Condition="'$(TargetFrameworkMoniker)' != '' and ('$(_TargetFrameworkDirectories)' == '' or '$(_FullFrameworkReferenceAssemblyPaths)' == '')"
TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
RootPath="$(TargetFrameworkRootPath)"
TargetFrameworkFallbackSearchPaths="$(TargetFrameworkFallbackSearchPaths)"
BypassFrameworkInstallChecks="$(BypassFrameworkInstallChecks)"
>
<Output TaskParameter="ReferenceAssemblyPaths" PropertyName="_TargetFrameworkDirectories"/>
<Output TaskParameter="FullFrameworkReferenceAssemblyPaths" PropertyName="_FullFrameworkReferenceAssemblyPaths"/>
<Output TaskParameter="TargetFrameworkMonikerDisplayName" PropertyName="TargetFrameworkMonikerDisplayName" Condition="'$(TargetFrameworkMonikerDisplayName)' == ''"/>
</GetReferenceAssemblyPaths>
The error message:
C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1221,5): Error MSB3644: The reference assemblies for .NETFramework,Version=v4.0 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks
Note: There are many similar post in SO that suggest to install VS2019. However, I am getting this message while running the application on Azure Pipelines.
Update
From your description, you are using the Microsoft host agent and the pipeline pop out issue 'cannot found NETFramework,Version=v4.0'.
Your environment looks like this:
https://github.com/actions/virtual-environments/blob/main/images/win/Windows2019-Readme.md#net-framework
or
https://github.com/actions/virtual-environments/blob/main/images/win/Windows2022-Readme.md#net-framework
You can see that the Microsoft host agent does not have the environment you mentioned.
Although you can install what you need at the beginning of the pipeline startup, I do not recommend this practice. Because when you choose microsoft host agent, every time you start the pipeline, you will be assigned a brand new azure VM machine, which means you need to install the relevant environment every time.
The recommended approach is to use a self-host agent. Please create a self-host agent based on your local machine (or another machine with the relevant environment), the steps are as follows:
https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/v2-windows?view=azure-devops
Provided above are the installation steps of windows self host agent, the steps should be very simple, if you encounter any problems please let me know.
And after that, you can run your pipeline based on that self host agent like this:
pool:
name: <your agent pool name>
If you are using classic pipeline, just click and select:
(If you run successfully on local, then the agent based on local machine should also be no problem.)
And if this is still unable to solve your issue, could you please remove the in-private information and share the YAML file or JSON file, and let me know at which step you encountered this issue?

gRPC as Windows Service

I am experimenting with gRpc and have it running. I am using .net core 3.1. C# . I am now attempting to install it as a windows service. The machine is Win 10 Pro x64 .
I added the line as instructed to run it as a windows service...
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
//https://learn.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/self-hosted
.UseWindowsService() // Enable running as a Windows service
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
I publish to a folder (I never have used publish before) and voila... there is the publish folder. I go to that folder and run (AS ADMINISTRATOR) installutil. Yes it found the utility as i used the full path. That path is
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe"
Is this correct version to run for .net core? Does that matter?
So I run installutil {full-path-to}\grpcservice1.exe
I get...
Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly
'file:///....\GrpcService1\GrpcService1\bin\Debug\netcoreapp3.1\publish\GrpcService1.exe'
or one of its dependencies. The module was expected to contain an
assembly manifest..
I can't figure out what I am doing wrong....
Suggestions? I just following the example.
TIA
installutil.exe looks for an Installer class marked with the RunInstallerAttribute set to true. It only works for Windows Services written with .NET Framework.
In the case of .NET Core, I'd recommend publishing your application and registering a new service using sc create/New-Service as you would in the case of any other executable.
There are also detailed docs in the .NET Core documentation in case you needed something more detailed.

Deploy a C# Stateful Service Fabric application from Visual Studio to Linux

EDIT 04/06/18 => Updated question with last status
So I have this working .Net 4.6 Stateful Service that currently run on my Windows Service Fabric cluster deployed on Azure.
Starting from 09/2017, I should be able to move to Linux: https://blogs.msdn.microsoft.com/azureservicefabric/2017/09/25/service-fabric-6-0-release/
So I'm trying to deploy it on Linux so I can save costs.
First things first, I've migrated all my code from .Net 4.6 to .Net Core 2.0. Now I can compile my binaries without issues. I've basically created new .Net Core projects and then moved all my source code from .Net 4.6 projects to the new .Net Core ones.
Then I've updated my Service Fabric application. I removed my previous SF services from my sfproj, then I've added my new .Net Core ones.
Looks like there is a warning (nothing on the output window though), but it's here anyway if I try to create a new empty Statful service using .Net core 2.0 through the template provided by Service Fabric Tools 2.0 (beta):
So I'm going to live with it.
On my dev machine, I've modified the 2 csproj projects that contain my Stateful services so they can run locally as Windows executables. I've used the win7-x64 runtimeIdentifier.
Running my SF cluster locally on my Windows machine is fine.
Then I've slightly changed the previous csproj files for Linux. I used the ubuntu.16.10-x64 runtimeIdentifier.
Also I've changed the ServiceManifest.xml file to target the linux-compatible binary:
<!-- Code package is your service executable. -->
<CodePackage Name="Code" Version="1.9.6">
<EntryPoint>
<ExeHost>
<Program>entryPoint.sh</Program>
</ExeHost>
</EntryPoint>
</CodePackage>
entryPoint.sh is a basic script that eventually executes:
dotnet $DIR/MyService.dll
Then I've successfully deployed to my secured SF Linux cluster from Visual Studio. Unfortunately I have the following errors for both my stateful services:
Error event: SourceId='System.Hosting',
Property='CodePackageActivation:Code:EntryPoint'. There was an error
during CodePackage activation.The service host terminated with exit
code:134
Looks like my binary crashes when starting. So here are my questions:
Is the approach right to deploy a C# .Net Core SF stateful service on Linux from Visual Studio?
EDIT: looking inside the LinuxsyslogVer2v0 table, I get the following error:
starthost.sh[100041]: Unhandled Exception:
System.IO.FileLoadException: Could not load file or assembly
'System.Threading.Thread, Version=4.1.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest
definition does not match the assembly reference. (Exception from
HRESULT: 0x80131040)
I found the following bug report: https://github.com/dotnet/sdk/issues/1502
Unfortunately, I still get the error without using MSBuild (using dotnet deploy).
EDIT: further clarification:
My boss want me to run on Linux because starting from D1v2 machines, it's half the price compared to Windows machines (no license etc.)
My .NET Core 2.0 services successfully run on Windows. So the .NET Core port should be fine.
So, this was a real pain in the ass to get it working properly. But it works. Well, kind of.
First, Reliable Services are still in preview on Linux: https://github.com/Microsoft/service-fabric/issues/71
Full Linux support should come very soon (actually it should be available already according to the previous link...).
Now for the details about how to procede, here is some information to help others, because there is just nothing about that on Microsoft documentation and I literally lost 3 days trying to make it work.
1. Do use .NET Core 2.0 for your projects.
It is supported on Linux. On preview for now, but it works.
2. Do use the right RID for your projects.
As of today (April 2018), the right RID to use is ubuntu.16.04-x64.
Edit the csproj files of your Reliable Service projects and set the RID like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
<RuntimeIdentifier>ubuntu.16.04-x64</RuntimeIdentifier>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
The fun part is, you should be able to provide multiple RIDs using the RuntimeIdentifiers parameter (with a S at the end) like that:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
<RuntimeIdentifiers>win7x64;ubuntu.16.04-x64</RuntimeIdentifiers>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
So you could build Windows binaries and Linux binaries at the same time.
But it simply doesn't work. When building the project from Visual Studio, I end up with the following directory only:
bin/Debug/netcoreapp2.0/
Only DLLs, no valid entry point. No win7-x64 folder, no ubuntu.16.04-x64, no nothing.
This is a bug, supposed to be fixed, but it's not (I use Visual Studio 15.6.2 all up-to-date as of today). See https://github.com/dotnet/core/issues/1039
3. You need a valid Entry Point for your service.
On Windows it's an executable file (*.exe). On Linux it's not. I ended up getting the Linux C# example and copied/pasted the entry point. https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-create-your-first-linux-application-with-csharp
So basically I now have on my ServiceManifest.xml file of each Reliable Service the following EntryPoint :
<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="XXXX"
Version="1.0.0"
xmlns="http://schemas.microsoft.com/2011/01/fabric"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ServiceTypes>
<!-- This is the name of your ServiceType.
This name must match the string used in RegisterServiceType call in Program.cs. -->
<StatefulServiceType ServiceTypeName="YYY" HasPersistedState="true" />
</ServiceTypes>
<!-- Code package is your service executable. -->
<CodePackage Name="Code" Version="1.0.0">
<EntryPoint>
<ExeHost>
<Program>entryPoint.sh</Program>
</ExeHost>
</EntryPoint>
</CodePackage>
entryPoint.sh is as follows:
#!/usr/bin/env bash
check_errs()
{
# Function. Parameter 1 is the return code
if [ "${1}" -ne "0" ]; then
# make our script exit with the right error code.
exit ${1}
fi
}
DIR=`dirname $0`
echo 0x3f > /proc/self/coredump_filter
source $DIR/dotnet-include.sh
dotnet $DIR/NAME_OF_YOUR_SERVICE_DLL.dll $#
check_errs $?
dotnet-include.sh is as follows:
#!/bin/bash
. /etc/os-release
linuxDistrib=$ID
if [ $linuxDistrib = "rhel" ]; then
source scl_source enable rh-dotnet20
exitCode=$?
if [ $exitCode != 0 ]; then
echo "Failed: source scl_source enable rh-dotnet20 : ExitCode: $exitCode"
exit $exitCode
fi
fi
Both are inside the PackageRoot folder. I specified for both their properties so the Build Action is "Content" and the Copy to Output Directory is "Copy always".
4. Do NOT build using MSBuild !!
Yeah it is supposed to build Linux packages too, or at least it seems so, because MSBuild is able to produce the following files when you right click on your project and click "Build":
Don't trust the apparent success of the operation, it will miserably FAIL to properly execute when deployed. Some *.so files missing and other issues. MSBuild is buggy as hell and misbehaves regarding dependencies.
See for instance this bug report: https://github.com/dotnet/sdk/issues/1502
Still not fixed after almost a year...
Or https://github.com/dotnet/core/issues/977 (got this one, too).
5. Do write some PowerShell script to build the stuff by yourself.
I ended up reinventing the wheel using the following script to build my package:
# Creating binaries for service 1
cd DIRECTORY_OF_MY_SERVICE_1
dotnet publish -c Release -r ubuntu.16.04-x64
# Creating binaries for service 2
cd ..\DIRECTORY_OF_MY_SERVICE_2
dotnet publish -c Release -r ubuntu.16.04-x64
# Creating binaries for service 3
cd ..\DIRECTORY_OF_MY_SERVICE_3
dotnet publish -c Release -r ubuntu.16.04-x64
# Copying ApplicationManifest.xml
cd ..
mkdir PKG\ServiceFabricApplication
echo F|xcopy "ServiceFabricApplication\ApplicationPackageRoot\ApplicationManifest.xml" "PKG\ServiceFabricApplication\ApplicationManifest.xml" /sy
# Copying Service1 files
mkdir "PKG\ServiceFabricApplication\Service1Pkg"
mkdir "PKG\ServiceFabricApplication\Service1Pkg\Code"
xcopy "Service1\PackageRoot\*" "PKG\ServiceFabricApplication\Service1Pkg" /sy /D
xcopy "Service1\bin\Release\netcoreapp2.0\ubuntu.16.04-x64\publish\*" "PKG\ServiceFabricApplication\Service1Pkg\Code" /sy
# Copying Service2 files
mkdir "PKG\ServiceFabricApplication\Service2Pkg"
mkdir "PKG\ServiceFabricApplication\Service2Pkg\Code"
xcopy "Service2\PackageRoot\*" "PKG\ServiceFabricApplication\Service2Pkg" /sy /D
xcopy "Service2\bin\Release\netcoreapp2.0\ubuntu.16.04-x64\publish\*" "PKG\ServiceFabricApplication\Service2Pkg\Code" /sy
# Copying Service3 files
mkdir "PKG\ServiceFabricApplication\Service3Pkg"
mkdir "PKG\ServiceFabricApplication\Service3Pkg\Code"
xcopy "Service3\PackageRoot\*" "PKG\ServiceFabricApplication\Service3Pkg" /sy /D
xcopy "Service3\bin\Release\netcoreapp2.0\ubuntu.16.04-x64\publish\*" "PKG\ServiceFabricApplication\Service3Pkg\Code" /sy
# Compresses the package
Write-host "Compressing package..."
Copy-ServiceFabricApplicationPackage -ApplicationPackagePath .\PKG\ServiceFabricApplication -CompressPackage -SkipCopy
sfproj file is a Visual Studio / MSBuild related project, so you need to build everything by yourself.
The script above produces the same content as the pkg folder created by MSBuild when building your sfproj using Visual Studio. It copies everything on a PKG folder at the root of your solution.
The package structure is detailed here: https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/service-fabric/service-fabric-package-apps.md
6. Now it's time to deploy!
At this point I didn't trusted Visual Studio anymore, so I built my own PowerShell script:
. .\ServiceFabricApplication\Scripts\Deploy-FabricApplication.ps1 -ApplicationPackagePath '.\PKG\ServiceFabricApplication' -PublishProfileFile '.\ServiceFabricApplication\PublishProfiles\Cloud.xml' -DeployOnly:$false -ApplicationParameter:#{} -UnregisterUnusedApplicationVersionsAfterUpgrade $false -OverrideUpgradeBehavior 'None' -OverwriteBehavior 'SameAppTypeAndVersion' -SkipPackageValidation:$false -ErrorAction Stop
It reuses the Deploy-FabricApplication.ps1 script provided by the Service Fabric project template inside the sfproj project. This script parses the Cloud.xml PublishProfile and deploys to your service fabric cluster.
So you specifies the rights values on both PublishProfiles/Cloud.xml and ApplicationParameters/Cloud.xml then execute the script.
It only works if you have the certificate used to secure the cluster installed on your machine, of course.
Do note the first dot '.' is important, because if you don't use it, you'll have the following error:
Get-ServiceFabricClusterManifest : Cluster connection instance is null
See https://stackoverflow.com/a/38104087/870604
Oh, and as there are bugs on the Service Fabric SDK too, you might want to shutdown your local SF cluster too...
https://github.com/Azure/service-fabric-issues/issues/821
7. Now it's time for another deception.
It simply doesn't work, the service crashes on startup. After searching hours inside the LinuxsyslogVer2v0 Azure Storage table (the log table for Linux, located in one of the two Azure Storage Accounts created automatically with the SF cluster), I found that Microsoft own Nuget Packages were buggy too.
Specifically, the Nuget package Microsoft.Azure.Devices doesn't work on version 1.6.0. An issue with a reference of a dll not found or whatever. I rollbacked to a previous version, namely 1.5.1, and it was fixed.
At this point I didn't had anymore energy to create another Github issue about that. Sorry MS, I'm not your QA team, I'm getting tired.
8. Build again using the first PowerShell script, deploy using the second PowerShell script, and you're done.
You've finally deployed C# Reliable Services using .NET Core 2.0 from Visual Studio (kind of, as it's buggy and I used PowerShell) on Windows to a Linux SF Cluster.
Now I still have issues with my ASP.NET Core service, but it will be a story for another day.
Conclusion: TL;DR
The whole thing is a mess. Bugs everywhere. In the SDK, in the tools, in some of Microsoft Nuget Packages. Awful experience. But it is supported (in preview for now) and you can make it work. Hope this post will help...
I was having similar issues, but I believe this is the issue:
In this release, .NET Core 2.0 services are only supported on Service Fabric for Windows. Full cross-platform support for .NET Core 2.0 services on Windows and Linux is coming soon.
From the Service Fabric 6.1 Release Notes
So no Linux as long as you are targeting .net core 2.0.
I have success deploy to Linux service fabric with this help
Open all the service .csproj files and update the RuntimeIdentifier as shown below
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
</PropertyGroup>
Update the ServiceManifest.xml to remove .exe extension as shown below
<CodePackage Name="Code" Version="1.0.0">
<EntryPoint>
<ExeHost>
<Program>Web1</Program>
</ExeHost>
</EntryPoint>
</CodePackage>
See https://blogs.msdn.microsoft.com/premier_developer/2018/05/27/running-net-core-2-0-applications-in-a-linux-service-fabric-cluster-on-azure/
*Visual Studio 15.7.3

How to run .net console application (built on windows) on Linux using .net core [duplicate]

I have a simple .NET Core project (console app) that I'm trying to compile and run. dotnet build succeeds, but I get the following error when I do dotnet run:
dotnet run
Project RazorPrecompiler (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
A fatal error was encountered. The library 'hostpolicy.dll' required to execute the application was not found in [path].
My project.json looks like this:
{
"buildOptions": {
"warningsAsErrors": true
},
"dependencies": {
"Microsoft.AspNetCore.Razor": "1.0.0",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
},
"description": "Precompiles Razor views.",
"frameworks": {
"netcoreapp1.0": {
"imports": [ ]
}
},
"version": "1.2.0"
}
What is hostpolicy.dll, and why is it missing?
Update for dotnet core 2.0 and beyond: the file appname.runtimeconfig.json (for both debug and release configuration) is needed in the same path as appname.dll.
It contains:
{
"runtimeOptions": {
"tfm": "netcoreapp2.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "2.0.0"
}
}
}
then dotnet.exe exec "path/to/appname.dll" [appargs] works.
This error message is unhelpful. The actual problem is a missing emitEntryPoint property:
"buildOptions": {
...
"emitEntryPoint": true
},
Once this is added, the compiler will let you know about any other problems (like a missing static void Main() method). Successfully compiling the project will result in an output that dotnet run can execute.
If I'm not mistaken, one scenario when you can hit the issue is this: You have an integration project that references another application project (not library). In this case, dependentProject.runtimeconfig.json won't be copied to your integration project's output folder and you won't be able to run dependentProject.exe binary because it will throw The library hostpolicy.dll was not found..
There is a Github issue for this and a workaround.
Edit: Should be fixed in .NET SDK 5.0.200.
I had similar problem running tests in VS19.
========== Starting test run ==========
Testhost process exited with error: A fatal error was encountered. The
library 'hostpolicy.dll' required to execute the application was not
found in 'C:\Program Files\dotnet'. Failed to run as a self-contained
app.
After digging into it I found the source of the problem:
The full path the the .runtimeconfig.json in the test binary folder was above 255 characters. Renaming the module, so the file path becomes shorter, resolved the problem.
This occurred when a Visual Studio 2019 preview upgrade .Net Core to the latest preview (specifically .Net Core 3.1.100-preview2-014569).
Reinstalling/repairing .Net Core 3.0.100 solved the problem for me.
I'm not sure why but I ran in to the problem when executing the .exe file in my \bin folder while the .exe in my \obj folder works fine.
I am having this problem in Dotnet Core 3.1 Console application.
If you are publishing your application, make sure that your target runtime set to the specific runtime that you had installed in your target machine.
If you set to portable it will pick whatever runtime that it feels comfortable (which you might not have it installed)
I had this happen with .NET 6.0 where somehow the appname.runtimeconfig.dev.json file was not being generated in the bin/Debug/net6.0/ directory.
The fix was modifying the .csproj file and include this fragment inside the <PropertyGroup> element:
<GenerateRuntimeConfigDevFile>true</GenerateRuntimeConfigDevFile>
I found this solution while searching with https://www.google.com/search?q=net60+runtimeconfig.dev.json at Breaking change: runtimeconfig.dev.json file not generated - .NET | Microsoft Learn with the solution at MSBuild properties for Microsoft.NET.Sdk - .NET | Microsoft Learn:
GenerateRuntimeConfigDevFile
Starting with the .NET 6 SDK, the [Appname].runtimesettings.dev.json file is no longer generated by default at compile time. If you still want this file to be generated, set the GenerateRuntimeConfigDevFile property to true.
<PropertyGroup>
<GenerateRuntimeConfigDevFile>true</GenerateRuntimeConfigDevFile>
</PropertyGroup>
After applying this to the .csproj file and re-building the project, debugging from Visual Studio Code worked fine including stopping at the breakpoints that I had set previously.
For me the issue was with the version mismatch. I had a different ".Net core SDK" version installed and a different version was specified in .json file.
Once I modified the version in my .json file the application started working fine.
In my case it was because I was publishing a self-contained application for the wrong target. My intent was to run on alpine linux, but I was building for libc when I should have been building for musl.
The failing package was built using:
dotnet publish --self-contained true --runtime linux-x64 --framework netcoreapp2.1 --output /app
Changing the RID:
dotnet publish --self-contained true --runtime linux-musl-x64 --framework netcoreapp2.1 --output /app
produced a functional package. Notice the RID changed from linux-x64 to linux-musl-x64. If I had read the .NET Core RID Catalog page this could have been avoided. 😅
Maybe you didn't want to do a "Console .Net Core" project but a "Console .Net Framework" project. It solves the problem, for me...
My problem was that I have 2 .NET Core App projects and one is dependent on the other.
(so I can then execute that application from that other application)
But .NET Core applications (with default config) need <assembly name>.runtimeconfig.json file (to get some launch config) which isn't copied by default.
The only solution that worked for me was adding to Project Properties > Build Events (of the dependent project) this command:
COPY "$(SolutionDir)<dependency name>\$(OutDir)<dependency assymbly name>.runtimeconfig.json" "$(SolutionDir)$(ProjectName)\$(OutDir)" /Y
But you can also copy the <dependency assembly name>.runtimeconfig.json file by hand to the dependent project.
Note that there should be a better more generic way to do this for every .NET Core App Project automatically.
This error is quite generic. So the real problem can be anything.
In my case (if helps anyone with same issue), I created a Class Library project instead of a Console Application project.
A Class Library DLL can't be runned with MSBuild, even if it has a Main method.
Only Console Application DDL can be runned as dotnet <appname>.dll
I was getting similar error while running Unit tests using VSTest#2 task in Azure Devops.
In my case, the problem was with my testAssemblyVer2 value. I was giving wrong pattern for test dlls.
Below one worked for me.(if you are getting this error with VSTest)
- task: VSTest#2
displayName: 'Running UnitTests'
inputs:
testSelector: 'testAssemblies'
testAssemblyVer2: |
$(System.DefaultWorkingDirectory)\SrcFolder\BBBB.UnitTests\**\bin\**\*.BBBB.UnitTests.dll
$(System.DefaultWorkingDirectory)\SrcFolder\AAAAa.UnitTests\**\bin\**\*.AAAA.UnitTests.dll
!**\*TestAdapter.dll
!**\obj\**
platform: x64
configuration: Debug
codeCoverageEnabled: true
So try to give correct pattern value for testAssemblyVer2 input. Make sure its filtering only the required dlls.
I had this same problem with a .NET Core 3.0 WPF app, but I found that my app wouldn't run in Visual Studio 2019 either.
I discovered on the project properties page (right-click on project > Properties) that the Target framework was set to .NET Core 3.0.
I'd recently updated VS 2019 which had also installed .NET Core 3.1, so I switched to that in the dropdown, and it worked again.
(I also had to update my shortcut to point to the netcoreapp3.1 folder instead of the previous netcoreapp3.0 folder.)
Promoting voltrevo's comment as an answer as I believe this should be the most common case of the problem. When you build your solution, sometimes you might get 2 directories with outputs bin and obj. 'Bin' directory has everything that is needed to run dotnet.exe command. Just run from the bin directory and things should be good. :)
For me with ASP.NET Core 2.0 on Azure, it was the appname.deps.json that did the trick. You need to copy it from your build directory to Azure.
For me, the error occurred during the SonarQube coverage scan due to one of the projects had a project reference to a MSTest project.
I faced this problem and it took me couple of days to figure out the solution.
Go to Visual Studio Installer.
Click on 'More' option of the Visual Studio.
Select 'Repair'.
It'll take some time for the download and installation.
Once it's completed restart the machine and try again.
This should solve the issue.
Add the OutputType on the PropertyGroup and issue is solved
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
more about this MSBuild can be found here

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