MVC: How to manage slahses in URL int the first route parameter

前端 未结 4 1461
忘掉有多难
忘掉有多难 2021-01-12 10:01

I need to map two variables that could contain slashes, to a controller, in my ASP MVC application. Let\'s see this with an example.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-12 10:07

    If you cannot live with "old fashioned" style parameters and URL encoding, I think the only way you can achieve it is like this. Note that this is not tested but should basically work. Also I've put the controller name at the start and the Items separator is now essentially meaningless apart from acting as a delimiter.

    Controller

    Create a controller with a single, parameterless method:

    public class GetRepo : Controller
    {
        public ActionResult Index()
        {
            //TBC
            return View();
        }
    }
    

    Routing

    Ensure routing is set up to allow http://www.example.com/GetRepo/anything to route to your index method.

    Note that the GetRepo part is important as otherwise what happens if your URL is www.example.com/blah/repo/items/other/stuff and you happen to have a controller called blah?

    The Magic

    Now you deconstruct the Url manually by using Request.Url.AbsolutePath.

    var urlPath = Request.Url.AbsolutePath;
    
    //Split the path by '/', drop the first entry as it's the action method
    var parts = urlPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
        .Skip(1).ToList();
    
    //Find where "Items" separator appears:
    var posOfItems = parts.IndexOf("Items");
    
    //Everything before separator is the repo:
    var repo = string.Join("/", parts.Take(posOfItems));
    
    //Everything after separator is the path:
    var path = string.Join("/", parts.Skip(posOfItems + 1));
    
    //Now do something with repo/path variables
    

提交回复
热议问题