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

在 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

posted @ 2019-11-16 22:06  dudu  阅读(1066)  评论(0编辑  收藏  举报