首页 > 解决方案 > Asp.Net Core [FromRoute] 自动 url 解码

问题描述

如果我们在 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...
}

是否有某种方法可以配置[FromRoute]解析行为,使其注入someParam已经解码的 url 值?

标签: c#asp.net-coreurlencode

解决方案


实现您想要做的任何事情的一种方法是创建自定义属性。在属性中,您基本上可以拦截传入的参数并执行您需要的任何操作。

属性定义:

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

在控制器中,您需要使用属性来装饰操作方法,如下所示。路线可根据您的需要进行修改。

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

需要注意的是,当您将编码字符串作为查询字符串参数传递时,您可能需要检查是否允许双重转义及其含义。


推荐阅读