Vik*_*nko 4 c# urlencode asp.net-core
如果我们在 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...
}
Run Code Online (Sandbox Code Playgroud)
是否有某种方法可以配置[FromRoute]解析行为,使其注入someParam已解码的 url 值?
实现您想要做的任何事情的一种方法是创建自定义属性。在属性内,您基本上可以拦截传入参数并执行您需要的任何操作。
属性定义:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在控制器中,您需要使用属性来装饰操作方法,如下所示。路线可以根据您的需要进行修改。
[HttpGet("/{param}")]
[Attributes.DecodeQueryParamAttribute]
public void Process([FromRoute] string param)
{
// value of param here is 'Blah'
// Action method
}
Run Code Online (Sandbox Code Playgroud)
需要注意的是,当您要将编码字符串作为查询字符串参数传递时,您可能需要检查是否允许双重转义及其含义。
| 归档时间: |
|
| 查看次数: |
7048 次 |
| 最近记录: |