如何将 ASP.NET 控制器 属性 与当前 URL 的一部分绑定?
How to bind an ASP.NET controller property with part of the current URL?
我正在使用 netcoreapp1.1 (aspnetcore 1.1.1)。
我想将 url 的一部分绑定到控制器 属性 而不是在操作参数中,可以吗?
例如:
获取: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
}
}
可以使用动作过滤器:
[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"
将在执行操作 Index
之前将 SomeProperty
设置为 "bar"
。
我正在使用 netcoreapp1.1 (aspnetcore 1.1.1)。
我想将 url 的一部分绑定到控制器 属性 而不是在操作参数中,可以吗?
例如: 获取: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
}
}
可以使用动作过滤器:
[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"
将在执行操作 Index
之前将 SomeProperty
设置为 "bar"
。