デプロイ前の前提条件
デプロイを開始する前に、以下の2つの前提条件を満たしているか確認してください。
1. IISモジュールのインストール
Windows 7の場合:
コントロールパネル → プログラムと機能 → Windowsの機能の有効化または無効化 → Internet Information Services(IIS)にチェックを入れてインストール
Windows Serverの場合:
コントロールパネル → プログラムと機能 → Windowsの機能の有効化または無効化 → 役割と機能の追加 → Webサーバー(IIS)を選択してインストール
2. AspNetCoreModuleのインストール
IISマネージャーの「モジュール」を確認し、「AspNetCoreModule」が含まれているか確認してください。
含まれていない場合は、.NET Core 2.1対応のモジュールをダウンロードしてインストールしてください。インストール完了後はシステムの再起動を推奨します。
IISサイトのデプロイ
上記の前提条件を満たしたら、通常通りのIISサイトデプロイを行います唯一的の違いはアプリケーションプールの設定です。「 managed codeなし」を選択してください。その他の設定は従来の.NETアプリケーションとほぼ同じです。
web.configのログ出力設定
正常に訪問できない場合は、web.configファイルにログ出力の設定を追加して原因を特定できます。
注意点として、デフォルトではlogsフォルダにログが出力されますが、このフォルダは自動作成されません。ログ出力を有効にするには、ログの出力をアプリケーションの実行ディレクトリ(.\)に変更し、stdoutLogEnabledをtrueに設定します。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\SampleApi.dll" stdoutLogEnabled="true" stdoutLogFile=".\" />
</system.webServer>
</location>
</configuration>
設定後、アプリケーションが正常に起動すれば、ログファイルが生成されます。
正常起動時のログ例
warn: Microsoft.AspNetCore.DataProtection.Repositories.EphemeralXmlRepository[50]
Using an in-memory repository. Keys will not be persisted to storage.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[59]
Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
No XML encryptor configured. Key {137dd630-fe50-4183-9121-e5952434ffd3} may be persisted to storage in unencrypted form.
Hosting environment: Production
Content root path: E:\websites\test.example.com
Now listening on: http://127.0.0.1:16972
Application started. Press Ctrl+C to shut down.
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
エラーケース1:SwaggerのHTTPメソッドBinding問題
以下のログは、Swaggerを使用する場合にアクションフィルターにHTTPメソッドの明示的な指定が必要であることを示しています。
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HLGBS6R1PEIL", Request id "0HLGBS6R1PEIL:0000000A": An unhandled exception was thrown by the application.
System.NotSupportedException: Ambiguous HTTP method for action - SampleApi.Controllers.HomeController.Index (SampleApi). Actions require an explicit HttpMethod binding for Swagger 2.0
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreatePathItem(IEnumerable`1 apiDescriptions, ISchemaRegistry schemaRegistry)
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath, String[] schemes)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
Application is shutting down...
解決策:
MVC APIコントローラーのでメソッドにHTTP属性を追加してください。例えば[HttpGet]や[HttpPost]を追加することで解决します。
[HttpGet]
public IActionResult Index()
{
return Ok();
}
エラーケース2:SQL Server接続エラー
以下のログは、データベースへの接続に失敗したことを示しています。
Application startup exception: Autofac.Core.DependencyResolutionException: An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = JobStorage (DelegateActivator), Services = [Hangfire.JobStorage], Lifetime = Autofac.Core.Lifetime.RootScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception: ネットワークパスが見つかりません。
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.Open()
at Hangfire.SqlServer.SqlServerStorage.CreateAndOpenConnection()
at Hangfire.SqlServer.SqlServerStorage.UseConnection[T](DbConnection dedicatedConnection, Func`2 func)
at Hangfire.SqlServerStorageExtensions.UseSqlServerStorage(IGlobalConfiguration configuration, String nameOrConnectionString)
at SampleApi.Startup.<>c__DisplayClass8_0.<ConfigureServices>b__1(IGlobalConfiguration configuration) in D:\Project\SampleApi\Startup.cs:line 77
at Hangfire.HangfireServiceCollectionExtensions.GetInitializedJobStorage(IServiceProvider serviceProvider)
at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
crit: Microsoft.AspNetCore.Hosting.Internal.WebHost[6]
Application startup exception
解決策:
このエラーはSQL Serverに接続できない場合に発生します。接続文字列の確認、SQL Serverサービスの状態確認、ファイアウォール設定の確認を行ってください。