ASP.NET CoreではModel - View - Controllerクラスが用意されています。
しかし、Serviceクラスのようなロジッククラスは用意されていませんので、自身でクラスを用意する必要があります。
その際に、Program.cs
に登録を忘れてしまうとアプリが起動できません。
なので、DI注入の方法について記載しておきます。
ディレクトリ構成
今回の記事で、DI注入するService
クラスはプロジェクトルート配下に配置しています。
└── Project/
├── bin
├── Controllers/
│ └── HomeController.cs
├── Models/
│ └── AdminUserViewModel.cs
├── Service/
│ └── PasswordHash.cs
├── Views/
│ └── Home/
│ ├── Index.cshtml
│ └── Privacy.cshtml
└── wwwroot
Program.csにServiceクラスを登録
Serviceクラス
をProgram.cs
に追加していきましょう。
注入した箇所は下記になります。
Program.cs
using ASPNETSQLServer.Service;
// ~(略)~
builder.Services.AddSingleton<PasswordHash>();
全体のProgram.cs
のコードは下記となります。
Program.cs
using ASPNETSQLServer.Service;
using Microsoft.AspNetCore.Identity; // PasswordHash サービスのnamespace
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<PasswordHash>();//追加
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Serviceクラスになにを書いたのか?
今回は、パスワードのハッシュ化をService
クラスに記載しました。
パッケージは下記を使っています。
PasswordHash.cs
using System;
using System.Security.Cryptography;
using System.Text;
namespace ASPNETSQLServer.Service;
public class PasswordHash
{
public string HashPassword(string password)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2"));
}
return builder.ToString();
}
}
}
サイト