c# - 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 值?
解决方案
实现您想要做的任何事情的一种方法是创建自定义属性。在属性中,您基本上可以拦截传入的参数并执行您需要的任何操作。
属性定义:
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
}
需要注意的是,当您将编码字符串作为查询字符串参数传递时,您可能需要检查是否允许双重转义及其含义。
推荐阅读
- azure - com.microsoft.windowsazure.mobileservices.MobileServiceException: {'code': 400}
- excel - 使用单元格的值和另一个文本字符串的条件格式
- javascript - 如何使用带有“或”确认的多个 Javascript 语句条件
- firebase - 在 Firestore 中,我需要在文档下创建多个记录
- plsql - dbms_parallel_execute.task_status 给出无效状态 4
- ruby - 用 Ruby 测试一个模块
- c# - 更新查询不起作用c#winform
- ios - 将 superView 拖到某个阈值后启用滚动 UITableView
- angular - 如何在 Angular 5 mat-table 中拼接数据?
- sql-server - 虚拟机之间无法连接sql server