これは、アクションフィルタで可能です:
[Route("{foo}/[controller]/{id?}")]
[SegmentFilter]
public class SegmentController : Controller
{
public string SomeProperty { get; set; }
public IActionResult Index(int id)
{
}
}
public class SegmentFilter : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(ActionExecutingContext context)
{
//path is "/bar/segment/123"
string path = context.HttpContext.Request.Path.Value;
string[] segments = path.Split(new[]{"/"}, StringSplitOptions.RemoveEmptyEntries);
//todo: extract an interface containing SomeProperty
var controller = context.Controller as SegmentController;
//find the required segment in any way you like
controller.SomeProperty = segments.First();
}
}
アクションIndex
が実行される前に、次に要求パス"myserver.com/bar/segment/123"
が"bar"
にSomeProperty
を設定します。