Search code examples
c#asp.net-coreurlencode

Asp.Net Core [FromRoute] auto url decode


If we have such controller endpoint in Asp.Net Core:

[HttpGet("/api/resources/{someParam}")]
public async Task<ActionResult> TestEndpoint([FromRoute] string someParam)
{
    string someParamUrlDecoded = HttpUtility.UrlDecode(someParam);
    // do stuff with url decoded param...
}

Is there some way to configure [FromRoute] parsing behavior in such way that it will inject into someParam already url decoded value?


Solution

  • One way to achieve whatever you're trying to do is to create a custom Attribute. Within the attribute you can essentially intercept the incoming parameter and perform whatever you need.

    Attribute Definition:

    public class DecodeQueryParamAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string param = context.ActionArguments["param"] as string;
            context.ActionArguments["param"] = "Blah"; // this is where your logic is going to sit
            base.OnActionExecuting(context);
        }
    }
    

    And within the controller, you'll need to decorate the action method with the attribute as done below. Route can be modified according to your need.

    [HttpGet("/{param}")]
    [Attributes.DecodeQueryParamAttribute]
    public void Process([FromRoute] string param)
    {
        // value of param here is 'Blah'
        // Action method
    }
    

    As a word of caution, when you are going to have encoded strings being passed as query string parameters, you may want to check about allowing Double Escaping and its implications.