ASP.NET Core 获取主机名时的 \"Decoded string is not a valid IDN name\" 错误

南楼画角 提交于 2019-12-04 16:25:32

在 ASP.NET Core 中通过 Request.Host.Host 获取主机名(hostname)时,如果主机名中包含非 ASCII 字符(比如 puny code),就会引发下面的异常:

System.ArgumentException : Decoded string is not a valid IDN name. (Parameter 'ascii')
Stack Trace:
    at System.Globalization.IdnMapping.ThrowForZeroLength(Boolean unicode)
at System.Globalization.IdnMapping.GetUnicodeCore(String asciiString, Char* ascii, Int32 count)
at System.Globalization.IdnMapping.GetUnicode(String ascii, Int32 index, Int32 count)
at System.Globalization.IdnMapping.GetUnicode(String ascii, Int32 index)
at System.Globalization.IdnMapping.GetUnicode(String ascii)
at Microsoft.AspNetCore.Http.HostString.FromUriComponent(String uriComponent)
at Microsoft.AspNetCore.Http.DefaultHttpRequest.get_Host()

改用 Request.Headers[HeaderNames.Host].ToString() 可以避开这个问题,但需要注意一个地方,用这个方法获取时,如果 url 中包含端口号(比如 https://localhost:5000),得到的主机名中也会包含端口号,比如 localhost:5000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!