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里面和这个类似,只是使用的属性不一样。

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

转载于:https://www.cnblogs.com/chimeile/p/WebApi-ActionFilter.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值