Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-mvc-routing

Object reference not set to an instance of an object - in route config file mvc


My Route Config file is

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;
        }
    }
}

I want to set value in Session from RouteConfig file. I am trying like this. But this throw an exception

Object reference not set to an instance of an object.

At this line

HttpContext.Current.Session["lang-code"] = s[0];

Here s[0] have value this is not null. What should i do to fix this exception.


Solution

  • This code is run when you app initially starts. At this point HttpContext.Current.Session is null so you can't assign a value to it.