Receive POST data other than UTF-8 encoded (ASP.NET MVC)

my ASP.NET MVC application is UTF-8, but I get a POST request in Encoding.Default from a third-party application out of my control.

What is the easiest and easiest way to modify a request for only one action of one controller ? (The rest of my application should remain 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(); } 
+6
source share
1 answer

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

  • Create your own 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); } } 
  • Put this on your action by specifying the desired encoding; in my case:

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

Source: https://habr.com/ru/post/909550/


All Articles