概要
AmazonLinux2023インスタンス上にコンテナで.NETを利用したサーバをたてる
そのお勉強メモ5
htmlをリターンするAPIルートを定義する
ソース
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "redis:6379";
});
builder.Services.AddControllers();
builder.Services.AddControllersWithViews(); // これ追加
var app = builder.Build();
app.MapGet("/", () => "Hello, World!");
app.MapControllers();
app.Run();
using Microsoft.AspNetCore.Mvc;
[Route("[controller]")]
public class ViewController : Controller
{
[HttpGet("{id}")]
public IActionResult Index(int id)
{
ViewBag.Message = $"id: {id}";
return View();
}
}
<!DOCTYPE html>
<html>
<head>
<title>index.cshtml</title>
</head>
<body>
<h1>@ViewBag.Message</h1>
</body>
</html>
実行テスト
xx.xx.xx.xx/view/1にアクセスして、「id : 1」と表示されればok
その他メモ
継承元の親クラスについて
今まで使っていたMysqlController等はControllerBase、ViewControllerはControllerが親クラスになっている
使い分けることが重要
クラス | 用途 | その他 |
---|---|---|
ControllerBase | textやjsonなどの文字列を返す。RestAPI用 | 軽量で高速 |
Controller | HTMLをView()やViewBagを使って返す。jsonも返せる | (CotrollerBaseよりは)重い |
View()関数の参照先HTMLファイル
return View();だけだと、以下の順で参照しに行く
ただし、引数に文字列を入れて、アクション名部分を変更することも可能
/Views/{コントローラー名}/{アクション名}.cshtml
/Views/Shared/{アクション名}.cshtml
[Route]属性について
コントローラ、アクションそれぞれにつけることでルーティング定義を行う
つけない場合
そのコントローラはルーティング設定されず404になる
ただし、Program.csにデフォルトルーティング設定をすることは可能
[Route("[controller]")]
コントローラ名が最上位ルートになる
以下の例だと/sample/{アクション名}
[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
[Route("hoge/[controller]")]
コントローラ名の前にプレフィックスを付けたルートになる
以下の例だとhoge/sample/{アクション名}
[ApiController]
[Route("hoge/[controller]")]
public class SampleController : ControllerBase
[Route("hoge")]
コントローラ名に限らず、固定ルートになる
以下の例だとhoge/{アクション名}
[ApiController]
[Route("hoge")]
public class SampleController : ControllerBase
[HttpGet("hoge")]
アクション名が関数名に関係しないルートになる
以下の例だとsample/hoge
[ApiController]
[Route("[controller]")]
public class SampleController : ControllerBase
{
[HttpGet("hoge")]
public string Get() => "Hello from sample/hoge";
}
[Route("[area]/[controller]/[action]")]
[controller]のようなプレースホルダー(ルートトークン)を組み合わせるとこんな指定も可能
以下の例だとhogeArea/sample/hogeAction
[Route("[controller]/[action]")]の指定が一番使い勝手良いのかも?
[Area("hogeArea")]
[Route("[area]/[controller]/[action]")]
public class SampleController : ControllerBase
{
[HttpGet]
public string hogeAction() => "hogehoge";
}