2017-05-23 1 views

Répondre

1

Il est possible avec un filtre d'action:

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

Ensuite, le chemin de la demande "myserver.com/bar/segment/123" sera mis à SomeProperty"bar" avant l'action Index est exécutée.