Automatic encoding of return HTML content in controller in ASP.NET CORE

Previously in ASP.NET MVC directly in the controller

   return Content( "<h1>Test test</h1>");

In the foreground VIEW, the bold text is displayed, but in ASP.NET CORE, it is directly returned as it is, and it automatically encodes it for you. The correct method should be the following code:

   return Content( "<h1>测试测试</h1>","text/html", Encoding.GetEncoding("GB2312"));

 

This code seems to be absent by default in CORE. It needs to be registered in the ConfigureServices method in Startup.cs. The code is as follows:

  //Add gb2312 support
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

 

 Then the above is just in the controller, if I rewrite the filter method in BaseController.cs, I have to use the following code:

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (HttpContext.Session.GetInt32("userid") == null)
            {
                var con = new ContentResult();

                //byte[] gb = Encoding.Unicode.GetBytes("Login timeout , please log in again!");
                //string r = "";
                //for (int i = 0; i < gb.Length; i += 2)
                //{
                // r += "\\u" + gb[i + 1].ToString("x").PadLeft(2, '0') + gb[i].ToString("x").PadLeft(2, '0');
                //}

                string r = "Login timed out, please log in again!";

                con.Content = $"<script>alert('{r}');parent.location.href='/login'</script>";
                con.ContentType = "text/html;charset=utf-8";

                context.Result = con;
            }
            base.OnActionExecuting(context);
        }

 

If you use the code in the comment, it is to convert all Chinese into the code starting with \u. .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326332426&siteId=291194637