locked
How to match the changed url segment RRS feed

All replies

  • User475983607 posted

    Use the catch-all parameter (**) which is covered in the ASP.NET Core routing documents.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.2#routing-basics

    https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.2

    Keep in mind the dynamic parameters must be at the end of the URL for obvious reasons.

    Wednesday, July 10, 2019 1:12 PM
  • User711641945 posted

    Hi gordanli,

    According to your request, you want to match the changed url segment like: http://localhost/api/XXX/.../values/0.

    Here is a working demo:

    1.Program RewriteRules.cs:

    public class RewriteRules
        {
            public static void ReWriteRequests(RewriteContext context)
            {
                var request = context.HttpContext.Request;
                var isMatch = Regex.IsMatch(request.Path.Value, @"^/api/(.*)/values/(\d+)");
                if (isMatch)
                {
                    var array = request.Path.Value.Split("/");
                    var length = array.Count();
                    context.HttpContext.Request.Path = "/api/values/" + array[length - 1];
                }
    
            }
        }

    2.Add app.UseRewriter() in Configure method in Startup.cs

    app.UseHttpsRedirection();
    
    app.UseRewriter(new RewriteOptions()
           .Add(RewriteRules.ReWriteRequests)
           );
    app.UseRouting();

    Attention: app.UseRewriter() must be written in front of app.UseRouting().

    3.Program ValuesController.cs:

    [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            [HttpGet("{id}")]
            public ActionResult<string> Get(int id)
            {
                return "value";
            }
       }

    Best Regards,

    Rena

    Thursday, July 11, 2019 9:47 AM