以非UTF-8编码接收POST数据(ASP.NET MVC)

时间:2022-06-05 04:03:17

my ASP.NET MVC Application is UTF-8, but I receive POST request in Encoding.Default from third-party app out of my control.

我的ASP.NET MVC应用程序是UTF-8,但是我在第三方应用程序的Encoding.Default中接收了POST控制请求。

What is sanest and simplest way to change request encoding for only one action of one controller? (Rest of my application should remain UTF-8).

为一个控制器的一个动作更改请求编码的最安全,最简单的方法是什么? (我的其他申请应保持UTF-8)。

public class Message
{
 public int id { get; set; }
 public string phone { get; set; }
 public string mes { get; set; }
 public string to { get; set; }
}

[HttpPost]
public ActionResult Receive(Message msg)
{
        AddIncomingMessage(msg);
        return new EmptyResult();
}

1 个解决方案

#1


-1  

I was struggling with the same problem, so after some research I came up with this solution:

我正在努力解决同样的问题,所以经过一些研究后我想出了这个解决方案:

  1. Create a custom Action Filter Attribute:

    创建自定义操作筛选器属性:

    public class CharsetAttribute : ActionFilterAttribute
    {
        private readonly string _charset = null;
    
        public CharsetAttribute() : this("UTF-8")
        {}
        public CharsetAttribute(string charset)
        {
            _charset = charset;
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Headers["Content-Type"] += string.Concat(";charset=", _charset);
        }
    }
    
  2. Put that on your action specifying the desired encoding; in my case:

    把它放在你指定所需编码的动作上;在我的情况下:

    [CharsetAttribute("ISO-8859-1")]
    public ActionResult MyAction(ThirdPartyViewModel model)
    { (...) }
    

#1


-1  

I was struggling with the same problem, so after some research I came up with this solution:

我正在努力解决同样的问题,所以经过一些研究后我想出了这个解决方案:

  1. Create a custom Action Filter Attribute:

    创建自定义操作筛选器属性:

    public class CharsetAttribute : ActionFilterAttribute
    {
        private readonly string _charset = null;
    
        public CharsetAttribute() : this("UTF-8")
        {}
        public CharsetAttribute(string charset)
        {
            _charset = charset;
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Headers["Content-Type"] += string.Concat(";charset=", _charset);
        }
    }
    
  2. Put that on your action specifying the desired encoding; in my case:

    把它放在你指定所需编码的动作上;在我的情况下:

    [CharsetAttribute("ISO-8859-1")]
    public ActionResult MyAction(ThirdPartyViewModel model)
    { (...) }