我的路线配置文件
using Aethtech.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Aethtech
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
string language = Langugae();
routes.MapRoute(
name: "Custom",
url: "" + language + "/{action}/{id}/{Title}",
defaults: new
{
controller = "Main",
action = "Default",
id = UrlParameter.Optional,
Title = UrlParameter.Optional
}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Main", action = "Default", id = UrlParameter.Optional }
);
}
public static string Langugae()
{
AethtechDataContext db = new AethtechDataContext();
CultureInfo culture = CultureInfo.CurrentCulture;
string language = culture.Name;
string[] s = language.Split('-');
var data = (from u in db.Languages
where u.code == language && u.is_active == true
select u).SingleOrDefault();
string lang = "";
if (data != null)
{
HttpContext.Current.Session["lang-code"] = s[0]; // Exception throw this line
lang = s[0];
}
else
{
HttpContext.Current.Session["lang-code"] = "en";
lang = "en";
}
return lang;
}
}
}
我想在Session
文件的RouteConfig
中设置值。
我这样想。但这会引发异常
Object reference not set to an instance of an object.
在这一行
HttpContext.Current.Session["lang-code"] = s[0];
此处s[0]
的值不是null
。
我该怎么做才能解决这个异常。
答案 0 :(得分:2)
此代码在应用最初启动时运行。此时HttpContext.Current.Session为null,因此您无法为其赋值。