Windows nano server iis

Introduction

The Nano Server is a remotely administered server operating system optimized for private clouds and data centers. It is similar to Windows Server in Server Core mode, but significantly smaller, has no local login capability, and only supports 64-bit applications, tools, and agents. It takes up far less disk space, sets up significantly faster, and requires far fewer updates and restarts than Windows Server. When it does restart, it restarts much faster. The Windows Server 2016, we are pleased to announce that IIS is now available as a role in Nano Server, for everyone to try out. With smaller memory and dramatically smaller disk footprint, web workloads are particularly suited to running on Nano Server, especially for high-density hosting.

IIS Administration PowerShell

The Windows 10 and Windows Server 2016, the IIS Team is releasing a new and simplified IIS Administration module side by side with the existing WebAdministration Cmdlets.

a1

Install the Internet Information Services (IIS) server role on Nano Server by using the -Package parameter with Microsoft-NanoServer-IIS-Package.

1 – Once the Nano Server Is running set remote host permissions If the Nano Server Is not part of the domain.

1. Start WinRM Service

2. Net start WinRM

3. Set-Item WSMan:\localhost\Client\TrustedHosts -Value “*”

1

2

2 – Now, Connect to the Nano Server via PowerShell

Enter-PSSession -ComputerName 192.68.0.21 -Credential Administrator

4

3 – Successfully connected Nano Server via PowerShell Console

2

4 – Mount Windows 2016 ISO as a drive in windows container host server.

6

5 – Copy the Nano Server package from Windows 2016 ISO to C:\packages folder on container host server. In this demonstration, the folder path is D:\NANOServerPackages folder.

7

6 – I will Install web server IIS using DISM 

dism /Mount-Image /ImageFile:”D:\HYPER-V\NANO-02\NANO-02.vhd” /Index:1 /MountDir:D:\Mountdir

8

7 – Now, we are Install on IIS Web Server package. run the line below to Install the package

dism /Add-Package /PackagePath:”D:\STUDY\Software Packages\NANOServerPackages\Microsoft-NanoServer-IIS-Package.cab” /Image:D:\mountdir

9

8 – Then unmount the VHD Nano Server with these commands

10

11

9 – In Hyper-V Manager, right click on the Nano Server VM and Click Start

Screenshot (3).png

10 – We are able to access the Nano server web Server (IIS) using Nano Server host IP Done, the site is running

Inked12_LI

Inked13_LI

Good luck! Just give it try – I’m sure you’ll love it as well. If you have any comments or questions on feel free to contact me.

That’s all for now. 🙂

iis

IIS on Windows Nano Server

This project is all about Windows Nano Server and Role IIS on a Docker Container.

We use as docker container base an unofficial repository on Docker Hub.
You can see here: https://hub.docker.com/u/nanoserver/

We always include Dockerfiles for Windows Containers — Docker.
As host OS we test on Windows 10 and Windows Server 2016 with Windows Containers Rol and Docker.

Getting started

Windows 10

Physical Machine or Virtual Machine
    Install Docker for 1.13.0-beta39 on your Windows 10 machine.

Windows Server 2016

Register into Microsoft evaluation Center. Download Windows Server 2016 Eval.
Get a Windows Server 2016 Virtual Machine
    Physical Machine / Virtual Machine
        Install on a physical machine or an virtual machine Windows Server and Containers, install Docker into Windows 2016 
    Azure
        Deploy Nano Server on Azure with docker-windows-azure templates.
        Create a Windows Server 2016 Core with Containers.

Welcome to Leap Year 2016. Have you ever wonder where is IIS 9.0 or 9.5? I do not know but it looks like 10 is Microsoft’s favourite number. Therefore, I’m introducing IIS 10.0 on Nano Server. Let us begin the journey with the deployment of IIS on Nano Server to basic IIS capability in creating a multiple new web sites on the Nano Server.

You can either view this article from the Microsoft TechNet Wiki which may have any improvement updates by the TechNet community on the link below;

  • http://social.technet.microsoft.com/wiki/contents/articles/33554.nano-server-deploying-an-internet-information-services-iis-web-server.aspx

Or carry on reading this page on the original article which I have noted in my engineering journal with some explanations on the process.

The Original TechNet Wiki Article on Nano Server: Building an Internet Information Services (IIS) Web Server

Introduction

In this article, we will demonstrate deploying an Internet Information Services (IIS) role on a Windows Server 2016 Technical Preview 4 Nano Server. Taking the advantage of Nano Server being a dedicated web server with a small disk footprint that is born in the cloud for the cloud.

Preparation of IIS for Nano Server Image

Joining Domain with Harvested BLOB

:: Harvest Machine (WS16TP4NSIIS1) Domain (naboo.co.nz) Join Blob from Domain Controller (WS16TP4ADDS1)
djoin /Provision /Domain naboo.co.nz /Machine WS16TP4NSIIS1 /SaveFile WS16TP4NSIIS1.djoin

Windows Nano Server - IIS - Build Process 1 - Harvest Domain BLOB

Copy the *.djoin file to your NanoServer folder

Getting Started with Nano Server (IIS and Domain Joined) Creation

In this example, we will create a Nano Server with IIS package that is joined to the Domain for DNS URL resolution capability.

# Import New-NanoServerImage PowerShell Module for Technical 
#  Preview 4
Import-Module `
    -Global C:\NanoServer\NanoServerImageGenerator.psm1 ;
# Create New Basic NanoServer Image with IIS for Technical 
#  Preview 4 with IIS Package
New-NanoServerImage `
    -MediaPath "Z:" `
    -BasePath "C:\NanoServer\Base" `
    -TargetPath "C:\NanoServer\WS16TP4NSIIS1\WS16TP4NSIIS1.vhd" `
    -EnableRemoteManagementPort `
    -Language "en-us" `
    -GuestDrivers `
    -DriversPath "C:\NanoServer\VMware-Drivers" `
    -Packages "Microsoft-NanoServer-IIS-Package" `
    -Ipv4Address "192.168.100.25" `
    -Ipv4SubnetMask "255.255.255.0" `
    -Ipv4Gateway "192.168.100.3" `
    -DomainBlobPath "C:\NanoServer\WS16TP4NSIIS1.djoin" `
    -AdministratorPassword (ConvertTo-SecureString `
           -String "Password" `
           -AsPlainText `
           -Force) ;

Windows Nano Server - IIS - Build Process 2 - Create Nano Server

Verify and obtain the Nano Server IP Address from the Nano Server Recovery Console

Windows Nano Server - IIS - Build Process 3 - View Nano Server TP4 Recovery Console

Verify the website is loading from another machine;

  1. Launch a Web Browser
  2. Input the IP Address of the Nano Server
  3. Verify that the IIS Default Website is loading

Windows Nano Server - IIS - Build Process 4 - View IIS Default Website

Manage Nano Server remotely using PowerShell Session

In this example, we will connect to Nano Server remotely using Enter-PSSession PowerShell Cmdlet to manage the Nano Server remotely and configure the Primary DNS Server Address and DNS Search Suffix List.

# Verify if the Nano Server is a Trusted Hosts
Get-Item `
    -Path WSMan:\localhost\Client\TrustedHosts ;
# Set the Nano Server IP Address to be a Trusted Hosts
Set-Item `
    -Path WSMan:\localhost\Client\TrustedHosts `
    -Value "192.168.100.24" `
    -Force ;
# Establish a remote PowerShell Session to the Nano Server
Enter-PSSession `
    -ComputerName 192.168.100.24 `
    -Credential (New-Object `
        -TypeName System.Management.Automation.PSCredential `
        -ArgumentList "192.168.100.24\Administrator", `
        (ConvertTo-SecureString `
            -String "Password" `
            -AsPlainText `
            -Force) `
    ) ;

Configure the Network Interface DNS Server configuration

In this example, it demonstrate on how to configure the Network Interface DNS Server Address and Search Suffix List. Unfortunately, we cannot use Resolve-DNSName PowerShell Cmdlet and therefore utilise the NSLookup instead.

# Get the network interface information on the Nano Server
Get-NetIPConfiguration ;
# Set the primary DNS server address on network interface 
#  on Nano Server
Set-DnsClientServerAddress `
    -InterfaceIndex 3 `
    -ServerAddresses ("192.168.100.11") ;
# Set the DNS search suffix list on Nano Server
Set-DnsClientGlobalSetting `
    -SuffixSearchList @("naboo.co.nz", "tatooine.co.nz") ;
# Verify Domain Name resolution is working using Nslookup 
#  instead of using Resolve-DNSName PowerShell Cmdlet 
#  because it is not available on Technical Preview 4
nslookup naboo.co.nz

Windows Nano Server - IIS - Build Process 5 - Change DNS Server

Once the Primary DNS Server Address and Search Suffix List has configured, you will need to ensure that the DNS Server has an A Record of the Nano Server Hostname. With the A Record of the Nano Server in the DNS Server, you will be able to verify the Default Website with the Hostname on Port 80.

Verify the website is loading from another machine;

  1. Launch a Web Browser
  2. Input the Hostname of the Nano Server
  3. Verify that the IIS Default Website is loading

Windows Nano Server - IIS - Build Process 6 - View IIS Default Website with Hostname

Getting Started with a new Web Site on Nano Server

In this example, we will demonstrate how to create another Web Site on IIS in Nano Server using the new IISAdministration PowerShell module with a custom web binding.

# Import IIS Administration PowerShell Module
Import-Module IISAdministration ;
# Create a folder
New-Item `
    -Path "C:\IIS-Site" `
    -Type directory ;
# Create a default page without ConvertTo-Html PowerShell 
#  Cmdlet because it is not available on Technical Preview 4
"Welcome to IIS on Nano Server by Ryen Tang (MVP)" | Out-File `
    -PSPath "C:\IIS-Site\Default.htm" ;
# Create a new IIS Website
New-IISSite `
    -Name "IIS-on-NanoServer" `
    -BindingInformation "*:80:iis.nanoserver.naboo.co.nz" `
    -PhysicalPath "C:\IIS-Site" ;
# Verify the new IIS Site is created
(Get-IISServerManager).Sites ;

Windows Nano Server - IIS - Build Process 7 - Create a new Website

Verify the website is loading from another machine;

  1. Launch a Web Browser
  2. Input the URL
  3. Verify that the new IIS Website is loading

Windows Nano Server - IIS - Build Process 8 - View new Website with URL

One of the driving forces behind the development of the IIS Administration API was Nano Server, a new headless variant of Windows Server 2016. This API allows us to provide a web based management UI. This post will cover the experience of getting IIS Administration up and running on Nano Server.

Enabling IIS

The first step to installing IIS Administration on a Nano machine is to make sure that the server has IIS enabled. We can enable IIS through the use of a package provider. First we must install the package provider, then install IIS, and finally restart the machine. We achieve this with the following PowerShell commands.

# Version of Nano Server used for this demo
[<NanoServerIPAddress>]: PS C:\> [System.Environment]::OSVersion
# Platform Version
# -------- -------
#   Win32NT 10.0.14300.0

# https://github.com/OneGet/NanoServerPackage
Save-Module -Path 'C:\Program Files\WindowsPowerShell\Modules\' -Name NanoServerPackage -minimumVersion 1.0.1.0
Import-PackageProvider NanoServerPackage
Install-NanoServerPackage -Name Microsoft-NanoServer-IIS-Package
Start-Service W3SVC

Verify

We can verify that IIS is installed and running on the machine by executing the following command.

Get-Service W3SVC | Select Status
# Status
# ------
# Running

Enable Dependencies

After we have installed IIS, we can enable the IIS components that IIS Administration depends on.

Pitfall: To avoid an issue with enabling IIS components, ensure that all desired components are enabled before making any modifications to the applicationHost.config file.

# Backup applicationHost.config
Copy-Item C:\Windows\System32\inetsrv\config\applicationHost.config C:\Windows\System32\inetsrv\config\applicationHost_BeforeIisAdministration.config
# Enable required features
Enable-WindowsOptionalFeature -Online -FeatureName "IIS-WindowsAuthentication"
Enable-WindowsOptionalFeature -Online -FeatureName "IIS-URLAuthorization"
# Optionally, take the chance to enable all IIS features
# Get-WindowsOptionalFeature -Online | where {$_.FeatureName -match "IIS-" -and $_.State -eq [Microsoft.Dism.Commands.FeatureState]::Disabled} | % {Enable-WindowsOptionalFeature -Online -FeatureName $_.FeatureName}

Installing .NET Core

In order to run IIS Administration, the machine must be set up to host .NET Core applications. There is a tutorial for installing .NET Core tailored specifically for Nano Server available at https://docs.asp.net/en/latest/tutorials/nano-server.html#installing-the-asp-net-core-module-ancm. The relevant sections are “Installing the ASP.NET Core Module (ANCM)” and “Installing .NET Core Framework.”

Copying the ASP.NET Core Module

To make copying the ASP.NET Core Module to the Nano Server machine easier, use the Copy-Item command combined with a PowerShell session.

$s = New-PSSession -ComputerName "<NanoServerIPAddress>" -UseSSL -Credential "<hostname>\Administrator"
Copy-Item C:\windows\system32\inetsrv\aspnetcore.dll -Destination c:\windows\system32\inetsrv\ -ToSession $s
Copy-Item C:\windows\system32\inetsrv\config\schema\aspnetcore_schema.xml -Destination C:\windows\system32\inetsrv\config\schema\ -ToSession $s

Adding .NET Core to Path

At this point .NET Core should be installed on the machine. Next we want to put the dotnet executable on the path so that .NET Core applications can be loaded by IIS without any manual intervention.

Note: Take caution when altering the PATH environment variable. This script stores the old value of the PATH environment variable for safe keeping.

# Assuming dotnet was placed at C:\Program Files\dotnet
$env:Path | Out-File "C:\PathBeforeDotNet.txt"
setx PATH "$($env:Path);C:\Program Files\dotnet" /m
# Restart computer to update path in IIS. Services' environments are not updated until system restart.
Restart-Computer –Confirm

Verify

At this stage we should verify that .NET Core has been added to the path correctly. We can do this by executing the following command.

Get-Command 'dotnet'
# Application  dotnet.exe  1.0.1.4500  C:\Program Files\dotnet\dotnet.exe

Then we can ensure that .NET Core is installed correctly by running the dotnet executable. Below is a snippet of the output of dotnet when executed alone.

dotnet
# Microsoft .NET Core Shared Framework Host
#   Version  : 1.0.1
#   Build    : cee57bf6c981237d80aa1631cfe83cb9ba329f12
# Usage: dotnet [common-options] [[options] path-to-application]

Opening the Firewall for Remote Administration

We want the API to be accessible by remote machines, therefore we need to allow it through the firewall. The default port is 55539 and we can open it up using PowerShell.

New-NetFirewallRule -Name "IIS Administration" -DisplayName "Allow IIS Administration on TCP/55539" -Protocol TCP -LocalPort 55539 -Action Allow -Enabled True

Visual Studio 2015 C++ Redistributable

To install the VS 2015 runtime libraries on Nano Server, install it on a local machine (x64 required) and then copy it over. This process is similar to the ASP.NET Core Module. The VS 2015 x64 C++ redistributable package can be obtained from https://go.microsoft.com/fwlink/?LinkID=827997. If the VS 2015 runtime is not installed, installation of the API will fail when trying to start the service.

First, on the Nano Server machine, check if the VS 2015 runtime is already installed

Write-Host "Visual Studio 2015 C++ Redistributable already installed?"
Write-Host "$(Test-Path C:\Windows\System32\vcruntime140.dll)"

If it is not installed, install it on the local machine and copy it over

# $s = New-PSSession -ComputerName "<NanoServerIPAddress>" -UseSSL -Credential "<hostname>\Administrator"
Copy-Item C:\Windows\System32\vcruntime140.dll -Destination C:\Windows\System32\ -ToSession $s

Installing the Microsoft IIS Administration API

The API can be obtained as a ZIP archive from https://github.com/Microsoft/IIS.Administration/releases/download/v1.0.36/IIS.Administration.zip. In this format, the API can be installed via a PowerShell script. Run this script to automatically download the archive and extract it to C:\IIS.Adminstration.

Download the Archive

$SourcePath = "https://github.com/Microsoft/IIS.Administration/releases/download/v1.1.1/IIS.Administration.zip"
$DestinationPath = "C:\IIS.Administration"
$EditionId = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'EditionID').EditionId
if ($EditionId -eq "ServerDataCenterNano") {
      $TempPath = [System.IO.Path]::GetTempFileName()
      if (($SourcePath -as [System.URI]).AbsoluteURI -ne $null) {
          Invoke-WebRequest -Uri $SourcePath -OutFile $TempPath
      }
      else {
          throw "Cannot copy from $SourcePath"
      }
      [System.IO.Compression.ZipFile]::ExtractToDirectory($TempPath, $DestinationPath)
      Remove-Item $TempPath
}

Install

Once the archive has been downloaded, assuming the default location was used, you can install the IIS Administration API by running the included setup script.

C:\IIS.Administration\setup\setup.ps1 Install –Verbose

Время на прочтение8 мин

Количество просмотров20K

Представляем первую из пяти статей, посвященных работе с ASP.NET Core: руководство по развертыванию приложения ASP.NET Core на Nano Server со службами IIS.

Первый цикл статей по ASP.NET Core

1. ASP.NET Core на Nano Server.
2. Создание внешнего интерфейса веб-службы для приложения.
3. Создание первого веб-API с использованием ASP.NET Core MVC и Visual Studio.
4. Развертывание веб-приложения в службе приложений Azure с помощью Visual Studio.
5. Ваше первое приложение на Mac c использованием Visual Studio Code.

Введение

Nano Server — это вариант установки Windows Server 2016, который имеет более компактный размер и более широкие возможности обслуживания и обеспечения безопасности по сравнению с Server Core и полным вариантом установки. Более подробная информация приведена в официальной документации по варианту установки Nano Server. Существует три способа начать с ним работу:

1. Загрузить ISO-файл Windows Server 2016 Technical Preview 5 и создать образ Nano Server.
2. Загрузить Nano Server VHD для разработчиков.
3. Создать виртуальную машину в Azure, используя образ Nano Server из Azure Gallery. Если у вас нет учетной записи Azure, вы можете создать бесплатную учетную запись с 30-дневным пробным периодом.

В данном материале используется заранее созданный Nano Server VHD для разработчиков из Windows Server Technical Preview 5.

Далее вам понадобится созданное и опубликованное 64-битное приложение ASP.NET Core.

Подготовка экземпляра Nano Server

Создайте новую виртуальную машину Hyper-V, используя предварительно загруженный файл VHD. Прежде чем войти в систему, необходимо задать пароль администратора. Для этого нужно нажать клавишу F11 в консоли виртуальной машины.

После создания пароля Nano Server может управляться удаленно при помощи PowerShell.

Удаленное подключение к экземпляру Nano Server при помощи PowerShell

Откройте окно PowerShell с повышенными привилегиями, чтобы добавить удаленный экземпляр Nano Server в список TrustedHosts.

$nanoServerIpAddress = "10.83.181.14"
Set-Item WSMan:\localhost\Client\TrustedHosts "$nanoServerIpAddress" -Concatenate -Force

Примечание: замените переменную $nanoServerIpAddress на используемый IP-адрес.

После добавления экземпляра Nano Server в список TrustedHosts выполните удаленное подключение к нему при помощи PowerShell.

$nanoServerSession = New-PSSession -ComputerName $nanoServerIpAddress -Credential ~\Administrator
Enter-PSSession $nanoServerSession

В случае успешного подключения появится командная строка следующего вида:

[10.83.181.14]: PS C:\Users\Administrator\Documents>

Создание каталога общего доступа

Создайте каталог общего доступа в экземпляре Nano Server, чтобы скопировать в него опубликованное приложение. В удаленном сеансе выполните следующие команды:

mkdir C:\PublishedApps\AspNetCoreSampleForNano
netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes
net share AspNetCoreSampleForNano=c:\PublishedApps\AspNetCoreSampleForNano /GRANT:EVERYONE`,FULL

После выполнения указанных команд вы сможете открыть каталог общего доступа, введя адрес \\<nanoserver-ip-address>\AspNetCoreSampleForNano в проводнике на хост-компьютере.

Открытие порта в брандмауэре

Выполните следующие команды в удаленном сеансе, чтобы открыть порт в брандмауэре:

New-NetFirewallRule -Name "AspNet5 IIS" -DisplayName "Allow HTTP on TCP/8000" -Protocol TCP -LocalPort 8000 -Action Allow -Enabled True

Установка IIS

Добавьте поставщика NanoServerPackage, выбрав его в коллекции PowerShell. После установки и импорта поставщика появится возможность устанавливать пакеты Windows.

Выполните следующие команды в PowerShell:

Install-PackageProvider NanoServerPackage
Import-PackageProvider NanoServerPackage
Install-NanoServerPackage -Name Microsoft-NanoServer-Storage-Package
Install-NanoServerPackage -Name Microsoft-NanoServer-IIS-Package

После установки компонента >Microsoft-NanoServer-Storage-Package требуется перезагрузка. Это временная процедура и она не будет нужна в будущем.

Чтобы быстро проверить, корректно ли установлены службы IIS, перейдите по адресу http://<nanoserver-ip-address>/ — должна отобразиться стартовая страница. При установке служб IIS создается веб-сайт по умолчанию под названием Default Web Site, для которого используется порт 80.

Установка модуля ASP.NET Core (ANCM)

Модуль ASP.NET Core — это модуль IIS 7.5+, который отвечает за управление работой прослушивателей (listeners) ASP.NET Core HTTP и передачу запросов к процессам, которыми он управляет. На данный момент установка модуля ASP.NET Core для IIS осуществляется вручную. Потребуется установить пакет .NET Core Windows Server Hosting на устройство с обычной операционной системой (не Nano Server). После установки пакета на компьютер с обычной операционной системой необходимо скопировать следующие файлы в каталог общего доступа, который был создан ранее.

На компьютере с обычной операционной системой (не Nano Server) выполните следующие команды копирования:

copy C:\windows\system32\inetsrv\aspnetcore.dll ``\\<nanoserver-ip-address>\AspNetCoreSampleForNano``
copy C:\windows\system32\inetsrv\config\schema\aspnetcore_schema.xml ``\\<nanoserver-ip-address>\AspNetCoreSampleForNano``

На виртуальной машине Nano Server необходимо скопировать следующие файлы из каталога общего доступа, который был создан ранее, в соответствующее расположение. Выполните следующие команды копирования:

copy C:\PublishedApps\AspNetCoreSampleForNano\aspnetcore.dll C:\windows\system32\inetsrv\
copy C:\PublishedApps\AspNetCoreSampleForNano\aspnetcore_schema.xml C:\windows\system32\inetsrv\config\schema\

Выполните следующий скрипт в удаленном сеансе:

# Backup existing applicationHost.config
copy C:\Windows\System32\inetsrv\config\applicationHost.config C:\Windows\System32\inetsrv\config\applicationHost_BeforeInstallingANCM.config

Import-Module IISAdministration

# Initialize variables
$aspNetCoreHandlerFilePath="C:\windows\system32\inetsrv\aspnetcore.dll"
Reset-IISServerManager -confirm:$false
$sm = Get-IISServerManager

# Add AppSettings section 
$sm.GetApplicationHostConfiguration().RootSectionGroup.Sections.Add("appSettings")

# Set Allow for handlers section
$appHostconfig = $sm.GetApplicationHostConfiguration()
$section = $appHostconfig.GetSection("system.webServer/handlers")
$section.OverrideMode="Allow"

# Add aspNetCore section to system.webServer
$sectionaspNetCore = $appHostConfig.RootSectionGroup.SectionGroups["system.webServer"].Sections.Add("aspNetCore")
$sectionaspNetCore.OverrideModeDefault = "Allow"
$sm.CommitChanges()

# Configure globalModule
Reset-IISServerManager -confirm:$false
$globalModules = Get-IISConfigSection "system.webServer/globalModules" | Get-IISConfigCollection
New-IISConfigCollectionElement $globalModules -ConfigAttribute @{"name"="AspNetCoreModule";"image"=$aspNetCoreHandlerFilePath}

# Configure module
$modules = Get-IISConfigSection "system.webServer/modules" | Get-IISConfigCollection
New-IISConfigCollectionElement $modules -ConfigAttribute @{"name"="AspNetCoreModule"}

# Backup existing applicationHost.config
copy C:\Windows\System32\inetsrv\config\applicationHost.config C:\Windows\System32\inetsrv\config\applicationHost_AfterInstallingANCM.config

Примечание: удалите файлы aspnetcore.dll и aspnetcore_schema.xml из каталога общего доступа после завершения предыдущего шага.

Установка .NET Core Framework

Если вы опубликовали переносимое приложение, платформа .NET Core должна быть установлена на целевом компьютере. Выполните следующие скрипты в удаленном сеансе Powershell, чтобы установить .NET Framework на виртуальной машине Nano Server:

$SourcePath = "https://go.microsoft.com/fwlink/?LinkID=809115"
$DestinationPath = "C:\dotnet"

$EditionId = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'EditionID').EditionId

if (($EditionId -eq "ServerStandardNano") -or
  ($EditionId -eq "ServerDataCenterNano") -or
  ($EditionId -eq "NanoServer") -or
  ($EditionId -eq "ServerTuva")) {

  $TempPath = [System.IO.Path]::GetTempFileName()
  if (($SourcePath -as [System.URI]).AbsoluteURI -ne $null)
  {
    $handler = New-Object System.Net.Http.HttpClientHandler
    $client = New-Object System.Net.Http.HttpClient($handler)
    $client.Timeout = New-Object System.TimeSpan(0, 30, 0)
    $cancelTokenSource = [System.Threading.CancellationTokenSource]::new()
    $responseMsg = $client.GetAsync([System.Uri]::new($SourcePath), $cancelTokenSource.Token)
    $responseMsg.Wait()
    if (!$responseMsg.IsCanceled)
    {
      $response = $responseMsg.Result
      if ($response.IsSuccessStatusCode)
      {
        $downloadedFileStream = [System.IO.FileStream]::new($TempPath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)
        $copyStreamOp = $response.Content.CopyToAsync($downloadedFileStream)
        $copyStreamOp.Wait()
        $downloadedFileStream.Close()
        if ($copyStreamOp.Exception -ne $null)
        {
          throw $copyStreamOp.Exception
        }
      }
    }
  }
  else
  {
    throw "Cannot copy from $SourcePath"
  }
  [System.IO.Compression.ZipFile]::ExtractToDirectory($TempPath, $DestinationPath)
  Remove-Item $Temp</code>
Path
}

Публикация приложения

Скопируйте опубликованное приложение в каталог общего доступа. Возможно, потребуется внести изменения в файл web.config, чтобы указать каталог, в который извлечен файл dotnet.exe. Другой способ — скопировать файл dotnet.exe в тот же каталог.

Пример файла web.config в ситуации, когда файл dotnet.exe не скопирован в тот же каталог:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
  <handlers>
   <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
  </handlers>
  <aspNetCore processPath="C:\dotnet\dotnet.exe" arguments=".\AspNetCoreSampleForNano.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true" />
 </system.webServer>
</configuration>

Выполните следующие команды в удаленной сессии, чтобы создать новый веб-сайт в IIS для опубликованного приложения. В этом скрипте для упрощения используется DefaultAppPool. Более подробная информация о работе с пулом приложений приведена в статье Application Pools.

Import-module IISAdministration
New-IISSite -Name "AspNetCore" -PhysicalPath c:\PublishedApps\AspNetCoreSampleForNano -BindingInformation "*:8000:"

Известная проблема в работе .NET Core CLI в Nano Server и способ ее обхода

Если используется Nano Server Technical Preview 5 c .NET Core CLI, необходимо скопировать файлы DLL из каталога c:\windows\system32\forwarders в каталог c:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.0\ и в каталог двоичных файлов .NET Core c:\dotnet (в данном примере). Это вызвано ошибкой, которая устранена в более новых версиях.

Если используется команда dotnet publish, скопируйте также файлы DLL из каталога c:\windows\system32\forwarders в каталог публикации.

Если система Nano Server Technical Preview 5 была обновлена или изменена, повторите данную процедуру, так как файлы DLL также могли быть обновлены.

Запуск приложения

Опубликованное веб-приложение должно быть доступно в браузере по адресу http://<nanoserver-ip-address>:8000. Если ведение журнала сконфигурировано так, как указано в разделе Создание и перенаправление логов, все журналы доступны в каталоге C:\PublishedApps\AspNetCoreSampleForNano\logs.

В данном материале используется предварительный выпуск варианта установки Nano Server, который доступен в Windows Server Technical Preview 5. Программное обеспечение на виртуальном образе жесткого диска может использоваться только для целей внутренней демонстрации и тестирования. Данное программное обеспечение не предназначено для использования в производственной среде. Дату окончания действия ознакомительной версии можно узнать здесь.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • 0x0000007b windows 7 при загрузке virtualbox
  • Как отключить сервис windows defender
  • Windows dlna server windows 7
  • Драйвер нвидиа для windows 10 последняя версия
  • Windows system32 winload efi 0xc000000e как исправить