WebApi中对请求参数和响应内容进行URL编码解码

时间:2023-03-08 15:14:10
WebApi中对请求参数和响应内容进行URL编码解码

项目经测试,发现从IE提交的数据,汉字会变成乱码,实验了网上很多网友说的给ajax加上contentType:"application/x-www-form-urlencoded; charset=UTF-8",发现没有用(ajax的请求标头确实变了,但是还是会乱码)

于是开始试验进行URL编码解码,一开始我是很不想这么干,因为这意味着我的后台也要对应的解码,现在没办法了,于是考虑用一个过滤器将客户端传过来的参数全部解码后再执行方法,没什么好说的,实现如下:

public class UrlDecodeFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{        var task = actionExecutedContext.Response.Content.ReadAsStringAsync();        HttpContent content = new StringContent(HttpUtility.UrlEncode(task.Result));

        actionExecutedContext.Response.Content = content;
        
base.OnActionExecuted(actionExecutedContext);

        }
public override void OnActionExecuting(HttpActionContext actionContext)
{
Dictionary<string, object> Param = actionContext.ActionArguments;
Dictionary<string, string> ParamTemp = new Dictionary<string, string>();
foreach (string item in Param.Keys)
{
object Value = Param[item];
if (Value == null)
continue;
string StrValue = Value.ToString();
if (string.IsNullOrEmpty(StrValue))
continue;
ParamTemp.Add(item, HttpUtility.UrlDecode(StrValue).Replace("??", ""));
}
foreach (var item in ParamTemp.Keys)
{
actionContext.ActionArguments[item] = ParamTemp[item];
}
base.OnActionExecuting(actionContext);
}
}

MVC里面和这个类似,只是使用的属性不一样。

对于为什么解码会出现“??”两个问号,我不知道,如果有知道的朋友希望不吝赐教