开发者

Detecting browser language and avoiding nullreference exception

开发者 https://www.devze.com 2023-02-27 06:12 出处:网络
I want to detect the browser language so I can switch languages when people connect to my website. But when a user hasnt filled in the langu开发者_StackOverflow中文版age in the browsers options I alwa

I want to detect the browser language so I can switch languages when people connect to my website. But when a user hasnt filled in the langu开发者_StackOverflow中文版age in the browsers options I always get a null value with

string browserlanguage = Request.UserLanguages[0]

How could I avoid the error "Object reference not set to an instance of an object."


Check for Request.UserLanguages != null.

For instance:

var l = Request.UserLanguages;
string browserlanguage = l ?? l[0] : "en";
// fall back to en, or set to "" or null.

Edit: (re your comment) If the above fails, too, Request itself was null, which afaik is impossible (could you check Request != null to make sure?). Did you possibly have a null reference later in your code?


string lang = (Request.UserLanguages ?? Enumerable.Empty<string>()).FirstOrDefault();
0

精彩评论

暂无评论...
验证码 换一张
取 消