如何强制MVC遵循完整的索引路由

时间:2017-06-04 09:56:59

标签: asp.net-mvc routeconfig

我正在开发多语言网站,一切正常,但问题是当我运行项目时,我有这个网址www.example.com,而我希望像www.example.com/一样例如法国的fr。 我有这个问题只是第一次索引页面渲染,我需要以某种方式重定向到这个www.example.com/fr路由,并强制它遵循路由配置

这是我的路线配置

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.Mvc;
 using System.Web.Routing;
 namespace global_vrf
 {
   public class RouteConfig
   {
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{language}/{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, language="" }
        );
    }
  }
 }

这是我的控制器

namespace global_vrf.Controllers
{


   public class HomeController : Controller
  {
    public ActionResult Index(string language)
    {

        if (String.IsNullOrWhiteSpace(language) == false)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
        }
        else if (String.IsNullOrWhiteSpace(language))
        {
            try
            {
                string userIpAddress = "this.Request.UserHostAddress";
                ViewBag.userIpAddress = userIpAddress;

                GeoIPService service = new GeoIPService();
                GeoIP output = service.GetGeoIP(userIpAddress);
                ViewBag.userIpAddress = userIpAddress;
                var country_name = output.CountryName;
                ViewBag.cnam = country_name;
                var country_code = output.CountryCode;
                ViewBag.ccode = country_code;

                if (country_code == "FRA")
                {
                    language = "fr-FR";
                    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
                    return View();
                }

                //and I will check the other languages here

            }
            catch
            {
                string userIpAddress = "209.95.51.176";
                ViewBag.userIpAddress = userIpAddress;

                GeoIPService service = new GeoIPService();
                GeoIP output = service.GetGeoIP(userIpAddress);
                ViewBag.userIpAddress = userIpAddress;
                var country_name = output.CountryName;
                ViewBag.cnam = country_name;
                var country_code = output.CountryCode;
                ViewBag.ccode = country_code;
                language = "en-us";

            }

        }

        return View();     
      }
    }
  }

0 个答案:

没有答案