Publish and Run an ASP.NET Core 1.0 Application in Production - asp.net-core

On an ASPNETCORE 1.0 application I have the following on Startup:
public Startup(IHostingEnvironment hostingEnvironment) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder
.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("settings.json", false, true)
.AddJsonFile($"settings.{hostingEnvironment.EnvironmentName}.json", false, true);
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
I have 2 settings files on my project:
settings.json
settings.production.json
I published the project using the command line:
set ASPNETCORE_ENVIRONMENT=production
dotnet publish --configuration Release
The published files include settings.json but not settings.production.json. And settings.json does include the properties which are only in settings.production.json. Shouldn't they be merged on publish?
In top of this how to make sure that the application runs on production mode when I copy the files to my server?
Do I need to do anything on Web.config?

You need to update your project.json to add your settings.production.json file to the include section of publishOptions:
{
"publishOptions": {
"include": [
"wwwroot",
"Views",
"Areas/**/Views",
"settings.json",
"settings.production.json",
"web.config"
]
}
}

Related

ASP.NET Core publishing to Azure (Staging)

VS 2019
ASP.NET Core 3.1
I have developed a Web App locally and now I am ready to deploy to an Azure Staging environment.
My Web App was originally .Net (not Core) and I had not problems deploying it.
How to I tell the deployment process to use the "Staging" environment?
My launchSettings.json contains the following:
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:59000",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
I have a appSettings.Staging.json pointing to the Staging database...
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Warning"
}
},
"ConnectionStrings": {
"DbConnection": "Data Source=myapp.database.windows.net;Initial Catalog=MyAppCoreStaging;user id=myappstepadmin;password=mypassword;MultipleActiveResultSets=True"
}
}
But I am not sure how to tell it to use Staging when I deploy.
At the moment when I deploy, the browser starts up on the page and I get:
HTTP Error 500.30 - ANCM In-Process Start Failure
Common solutions to this issue:
The application failed to start
The application started but then stopped
The application started but threw an exception during startup
Troubleshooting steps:
Check the system event log for error messages
Enable logging the application process' stdout messages
Attach a debugger to the application process and inspect
For more information visit: https://go.microsoft.com/fwlink/?LinkID=2028265
Is there something I need to configure on Azure to use the Staging?
Since you are deploying to Azure and didn't specify that you are using a CI/CD Pipeline as your method of publishing, I assume that you are using the publishing profiles provided from Azure portal directly in Visual Studio.
In the Publish dialog, click on Edit -> settings -> Configuration and select Stage
In your Program.cs, your CreateWebHostBuilder (assuming you are using ASP.NET Core 3.0+; it's also possible for 2.2 but it's not IWebHostBuilder), you can specify that the appsettings file should be dependent on your solution configuration:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseEnvironment(Environment);
where Environment can be a property with preprocessor directives:
public static string Environment
{
get
{
string environmentName;
#if DEBUG
environmentName = "development";
#elif STAGE
environmentName = "staging";
#elif RELEASE
environmentName = "production";
#endif
return environmentName;
}
}
If you use a build pipeline, you should look at this.
steps:
- task: DotNetCoreCLI#2
inputs:
command: 'publish'
publishWebProjects: true
arguments: '-o $(build.artifactstagingdirectory) /p:EnvironmentName=Staging'

dotnet pack - defining output folders

I'm using dotnet pack to create a nuget package for a .net core project but have 2 issues:
The .nupkg file when inspected always has a lib folder which contains the contents of the project's bin folder. Can you prevent the lib folder from being created in the output?
In the project.json packOptions how do you map an include folder to an output directory? I've tried using the mappings property as detailed below to output the contents of the publish directory into the wwwroot directory below but no luck so far.
"packOptions": {
"files": {
"include": [
"publish"
],
"mappings": {
"wwwroot": "publish"
}
}
},
I was unable to remove the lib folder but the mapping works with slight modifications to the example above as displayed below:
"packOptions": {
"files": {
"include": [
"publish"
],
"mappings": {
"wwwroot/": "publish/"
}
}
}

Gulp task to web deploy from Visual Studio

I have not found a concrete example on how to do the publishing via a Gulp Task. Anyone has an idea?
This is how i'm trying at the moment.
gulp.task("Deploy-To-Azure", function() {
var targets = ["Build"];
console.log("Publishing to Azure");
return gulp.src(["./src/Feature/Accounts/code"])
.pipe(foreach(function (stream, file) {
return stream
.pipe(debug({ title: "Building project:" }))
.pipe(msbuild({
targets: targets,
configuration: "Azure",
logCommand: false,
verbosity: "verbose",
stdout: true,
errorOnFail: true,
maxcpucount: 0,
toolsVersion: 14.0,
properties: {
DeployOnBuild: "true",
DeployDefaultTarget: "Web Deploy",
WebPublishMethod: "FileSystem",
DeleteExistingFiles: "false",
_FindDependencies: "false",
Configuration: "Release"
}
}))
.pipe(debug({title: "Finished building project"}));
}));
});
But it looks like the project is built but not deployed. I think my properties are not complete. Any ideas are appreciated. Thank you
I attempted to use those same MSBuild properties from the commandline and received the following error:
>c:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild /p:DeployOnBuild=true /p:WebPub
lishMethod=FileSystem /p:DeleteExistingFiles=false /p:DeployDefaultTarget="Web Deploy"
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.P
ublishing.targets(4449,11): error MSB4057: The target "Web Deploy" does not exi
st in the project. [c:\users\me\documents\visual studio 2015\projects\w
ebapplication12\WebApplication12.csproj]
Unless you've created a custom MSBuild Target named "Web Deploy". This won't work.
When I remove the /p:DeployDefaultTarget="Web Deploy" property a WebDeploy package is created in the /obj/[configuration]/Package folder.
Try DeployDefaultTarget: "WebPublish"

Nancy support for .NETCoreApp

Trying to add the Nancy package to a new project. In project.json (dependencies segment) red squigly under "Nancy": "1.4.3". Mouseover displays an error relating to support for .NETCoreApp
The master branch of Nancy on github already runs on .net core.We are moving from Rake to Cake for the build script , hoping to wrap that up this week so .netcore support can be pushed to Nuget.So yes wait just a bit.
This example was original written on Stack Overflow Documentation:
Setup Nancyfx with Dotnet core v1.1, Kestrel, and Visual Studio Code on *nix systems
Prerequiste steps:
Get dotnet core for your platform:
Dotnet Core
Follow instructions and make sure dotnet core is working
Get Visual Studio Code for your platform:
VS Code
Launch Visual Studio Code (VS code) and install the C# extension then reload
Create self hosted NancyFx project:
Setup a project with a correct project directory structure.
Open Bash Terminal and type:
mkdir nancydotnetcore
cd nancydotnetcore
mkdir src
mkdir test
touch global.json
Open global.json and enter the following code:
{
"projects":["src", "test"]
}
In Bash terminal:
cd src
mkdir NancyProject1
dotnet new
Open folder NancyProject1 in VS code
You will get a warning: "Required assets to build and debug are missing from 'nancyproject1'."
Click "Yes"
Also you will see: There are unresolved dependencies from 'project.json'. Please execute the restore command to continue.
Click "Close" we will get to this soon.
Add the dependencies, open "project.json" and overwrite it with the following:
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"frameworks": {
"netcoreapp1.1": {
"dependencies": {
"Microsoft.AspNetCore.Hosting": "1.1.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
"Microsoft.AspNetCore.Owin": "1.1.0",
"Nancy": "2.0.0-barneyrubble",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
}
}
}
}
VS code will ask to restore click "Restore"
Create folder "Modules" in VSCode project
In the Modules folder add a file named "IndexModule.cs" then copy and save the following:
namespace NancyProject1
{
using Nancy;
public class IndexModule : NancyModule
{
public IndexModule()
{
Get("/", _ => "Hello dotnet core world!");
}
}
}
In the root directory of the project create a file called "Startup.cs" and copy and paste the following:
namespace NancyProject1
{
using Microsoft.AspNetCore.Builder;
using Nancy.Owin;
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseOwin(x => x.UseNancy());
}
}
}
Open file "Program.cs" and overwrite the content with the following and save:
namespace NancyProject1
{
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseKestrel()
.UseStartup()
.Build();
host.Run();
}
}
}
Done! Now lets run this and see the output.
Click the debug symbol in VS Code, and Click the run button. It should compile and start the project.
Open the browser # http://localhost:5000
Pat yourself on the back and enjoy!
still pre release version but works with .net core as the time of this writing, view engines are very limited on core.
Install-Package Nancy -Version 2.0.0-barneyrubble -Pre

ASP .NET 5 Empty Project returns 500 Internal Server Error

I've created a new Web Application, using the empty ASP .NET 5 preview template. The project builds after I run dnu restore.
When I run it, I get an empty response (i.e. blank page). Refreshing the page, I get a "HTTP Error 500.0 - Internal Server Error" typical page with no useful info (see screenshot below).
I'm using the standard boilerplate code from the project template:
public class Startup
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
I noticed that if I set a breakpoint, it tells me the breakpoint won't be hit.
What am I doing wrong, and how can I get this simplest of scenarios working?
Edit: project.json is the default one that comes with the project template (uses beta 5, which I know is not the latest):
{
"webroot": "wwwroot",
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta5",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta5"
},
"commands": {
"web": "Microsoft.AspNet.Hosting --config hosting.ini"
},
"frameworks": {
"dnx451": { },
"dnxcore50": { }
},
"publishExclude": [
"node_modules",
"bower_components",
"**.xproj",
"**.user",
"**.vspscc"
],
"exclude": [
"wwwroot",
"node_modules",
"bower_components"
]
}
It's just crazy what I had to go through to make this work. Summary:
Go to %userprofile%, delete everything in .dnx\packages (just to make sure there aren't conflicts between different beta runtime versions)
Make sure latest runtime is being used
dnu restore
Replace dependencies in project.json as per this answer
As per comment below that answer, replace "Microsoft.AspNet.Hosting --config hosting.ini" with "Microsoft.AspNet.Server.Kestrel"
In Startup.cs, replace using Microsoft.Framework.DependencyInjection; with using Microsoft.Extensions.DependencyInjection;
Run project with command line invoking dnx web, NOT from Visual Studio
Moral of the story: the "preview template" that comes with Visual Studio is WAY out of date, and you're better off starting a fresh project.
Note: at the time of writing, the latest runtime is 1.0.0-rc1-update1.