在 .NET MVC中,有时候需要使用httpstatuscoderesult 返回状态描述,那么这个时候就有可能遇到乱码问题,除非你使用英文。其实也挺好解决的,解决MVC 中httpstatuscoderesult 通过StatusDescription 返回中文乱码。
c#中httpstatuscoderesult语法如下:
public HttpStatusCodeResult( HttpStatusCode statusCode, string statusDescription )
在Action中通过
return new HttpStatusCodeResult(HttpStatusCode.BadRequest,"我是中文字符串")
在前端返回的是乱码,原因是根据 http 协议,StatusDescription 是写在 http header 中的,默认所有header是用iso-8859-1编码的,但是中文实际是用uft8编码。所以就出现了乱码问题。
解决方法是使用转码把UTF8编码转为iso-8859-1编码。
////// 转换为ISO_8859_1 /////////private string StringToISO_8859_1(string srcText) { string dst = ""; char[] src = srcText.ToCharArray(); for (int i = 0; i < src.Length; i ) { string str = @"&#" (int)src[i] ";"; dst = str; } return dst; } ////// 转换为原始字符串 /////////private string ISO_8859_1ToString(string srcText) { string dst = ""; string[] src = srcText.Split(´;´); for (int i = 0; i < src.Length; i ) { if (src[i].Length > 0) { string str = ((char)int.Parse(src[i].Substring(2))).ToString(); dst = str; } } return dst; }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。