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

时间:2017-05-23 14:43:21

标签: asp.net asp.net-core-mvc asp.net-mvc-routing

我正在使用netcoreapp1.1(aspnetcore 1.1.1)。

我想将url的一部分绑定到控制器属性而不是动作参数,是否可能?

例: GET:https://www.myserver.com/somevalue/users/1

public class UsersController {
    public string SomeProperty {get;set;} //receives "somevalue" here

    public void Index(int id){ 
        //id = 1
    } 
}

1 个答案:

答案 0 :(得分:1)

可以使用动作过滤器:

[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"设置为Index