如何将ASP.NET控制器属性与当前URL的一部分绑定?

如何将ASP.NET控制器属性与当前URL的一部分绑定?,asp.net,asp.net-core-mvc,asp.net-mvc-routing,Asp.net,Asp.net Core Mvc,Asp.net Mvc Routing,我正在使用netcoreapp1.1(AspNetCore1.1.1) 我想将url的一部分绑定到控制器属性,而不是在操作参数中,可以吗 例: 获取: 可以使用操作过滤器: [Route("{foo}/[controller]/{id?}")] [SegmentFilter] public class SegmentController : Controller { public string SomeProperty { get; set; } public IActionR

我正在使用netcoreapp1.1(AspNetCore1.1.1)

我想将url的一部分绑定到控制器属性,而不是在操作参数中,可以吗

例: 获取:


可以使用操作过滤器:

[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();
    }
}
然后,在执行操作
索引之前,请求路径
“myserver.com/bar/segment/123”
SomeProperty
设置为
“bar”

[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();
    }
}