pet*_*man 5 asp.net asp.net-web-api
我有一个具有以下签名的 ASP.NET WebAPI 控制器操作:
public async Task<HttpResponseMessage> GetFoo(string something=null)
Run Code Online (Sandbox Code Playgroud)
当使用以下查询字符串调用此函数时:GetFoo?something=%20我希望使用以下命令调用该操作:something = " "但相反,某些内容被设置为 null。
如何使控制器操作接受%20带有单个空格的字符串并将其传递到我的应用程序?
这非常令人惊讶,但你是对的。看来 MVC 会解析出路由值中的单个空格。
我为您提供了一个解决方案,但这更多的是一种解决方法,而不是实际的答案。
添加这个类:
public sealed class AllowSingleSpaceAttribute : ActionFilterAttribute
{
private readonly string _routeValueName;
public AllowSingleSpaceAttribute(string valueName)
{
_routeValueName = valueName;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
if (context.ActionArguments.ContainsKey(_routeValueName))
{
if (context.HttpContext.Request.Query[_routeValueName] == " ")
{
context.ActionArguments[_routeValueName] = " ";
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样装饰你的控制器:
[AllowSingleSpace("something")]
public async Task<HttpResponseMessage> GetFoo(string something=null)
{
...
}
Run Code Online (Sandbox Code Playgroud)
你会得到你想要的东西,但它闻起来很臭!我很想了解发生这种情况的原因。
| 归档时间: |
|
| 查看次数: |
579 次 |
| 最近记录: |