.NET 6 Core API のカスタム属性
カスタム属性は非常に使いやすく、私はごく最近使い始めました。カスタム属性を使用すると、カスタム属性を 1 つ作成し、コントローラー、クラス、またはメソッド自体で再利用できるからです。
これらは、ヘッダーのチェックなどのセキュリティ関連の作業を行う場合や、絶対に必要なパラメーターの値を確認する場合に非常に役立ちます。
私の場合は、.NET Core API プロジェクトでこれを使用し、すべてのリクエストに特定のヘッダーが含まれているかどうかを確認します。
HeaderCheckAttribute
クールな .NET Core API を作成したら、フォルダーを使用するのが好きなので、内容を保存するフォルダーを作成しましょう。

次に、ロジックを HeaderCheckAttribute クラスに追加します。
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace DotNet6CustomAttribute.Attributes
{
public class HeaderCheckAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
// Get all headers
var headers = context.HttpContext.Request.Headers;
// Check if headers has x-dotnet-6-custom-attribute
if (!headers.ContainsKey("x-dotnet-6-custom-attribute"))
{
context.Result = new BadRequestObjectResult("The header x-dotnet-6-custom-attribute is missing");
}
else if (string.IsNullOrEmpty(headers["x-dotnet-6-custom-attribute"]))
{
context.Result = new BadRequestObjectResult("The header x-dotnet-6-custom-attribute can't be null or empty");
}
base.OnActionExecuting(context);
}
}
}
基本的なロジックは、まずキー x-dotnet-6-custom-attribute を持つヘッダーをチェックし、存在する場合は値があるかどうかをチェックします。
これらの式が両方とも true の場合、特定のメッセージを含む BadRequestObjectResult が返されます。
コントローラーに追加する
このロジックは複数の場所に追加することも、コントローラー全体に直接追加することも、一部のメソッドに追加することもできます。最初にメソッドに追加し、次にコントローラー全体に追加します。
それでは、WeatherForecastController クラスをそれらで装飾しましょう。
using DotNet6CustomAttribute.Attributes;
using Microsoft.AspNetCore.Mvc;
namespace DotNet6CustomAttribute.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
[Route("GetWeatherForecastWithCheck")]
[HeaderCheckAttribute]
public IEnumerable<WeatherForecast> GetWithCheck()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
[HttpGet]
[Route("GetWeatherForecastWithoutCheck")]
public IEnumerable<WeatherForecast> GetWithoutCheck()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
プロジェクトを実行しましょう!

そこには GetWeatherForecastWithCheck と GetWeatherForecastWithoutCheck という 2 つの関数があります。そのうちの 1 つは失敗し、もう 1 つは失敗しません。しかし、Swagger で確認してみましょう。

ご覧のとおり、一方はメッセージとともに 400 エラーを返し、もう一方は値を返します。これを完全にテストするために、Postman を実行してヘッダーを追加し、GetWeatherForecastWithCheck を使用してデータも確認できるようにします。
#郵便屋さん
Postman で実行中、ヘッダーを追加すると、ヘッダーは提供していますが、値が存在しないため、エラー メッセージが変更されていることがわかります。

それに値を追加すると、最終的に値が得られます。

#それだけです
それはそれです!かなりシンプルですよね?これで、属性を作成してメソッドとコントローラーに割り当てる方法がわかりました。
彼らと一緒に楽しんでください!
コード
このプロジェクト全体は Github にあり、ここ で見つけることができます。
問題や質問がある場合は、ソーシャル メディアで @emimontesdeoca までお気軽にご連絡ください (Twitter では実際には @emimontesdeocaa で最後に aa が 2 つ付いています)。私のソーシャルのほとんどはブログのヘッダーからも見つけることができます。
投稿が気に入っていただければ幸いです!キャー!