ASP.NET Core 依存関係の挿入(@inject)で実行するメソッド内では、Userだけではなく、HttpContext、Sessionも取得できずnullになるので、ビューからパラメータで渡す。
下記は、ASP.NET Core 2.2 で、_Layout.cshtmlビューで実行する依存関係の挿入クラス(@inject UserSettingService UserSetting)に、セッションオブジェクト(HttpContext.Session)をパラメータで渡した例。
下記は、ASP.NET Core 2.2 で、_Layout.cshtmlビューで実行する依存関係の挿入クラス(@inject UserSettingService UserSetting)に、セッションオブジェクト(HttpContext.Session)をパラメータで渡した例。
_Layout.cshtml
@using WebAppTest.Common
@using WebAppTest.Services
@using Microsoft.AspNetCore.Http
@inject UserSettingService UserSetting
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test</title>
@using WebAppTest.Services
@using Microsoft.AspNetCore.Http
@inject UserSettingService UserSetting
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
crossorigin="anonymous"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" />
</environment>
@if (UserSetting.BackgroundColor(User, Context.Session) == BackgroundColor.White)
{
<link id="cssfile" rel="stylesheet" href="~/css/site.css" />
}
else
{
<link id="cssfile" rel="stylesheet" href="~/css/site-black.css" />
}
</head>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"
crossorigin="anonymous"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" />
</environment>
@if (UserSetting.BackgroundColor(User, Context.Session) == BackgroundColor.White)
{
<link id="cssfile" rel="stylesheet" href="~/css/site.css" />
}
else
{
<link id="cssfile" rel="stylesheet" href="~/css/site-black.css" />
}
</head>
最近のコメント