How to add subdomain for Area in mvc?
I have a web application using asp.net MVC and have multiple Areas:
- localhost
- localhost/admin/home/index
- localhost/tech/home/index
How can I add a subdomain for this Areas? example:
- localhost
- admin.localhost/home/index
- admin.tech/home/index
Resolve:
1. Create class SubDomainRoute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Web.App_Start
{
public class SubDomainRoute : Route
{
private readonly string[] namespaces;
public SubDomainRoute(string url, object defaults, string[] namespaces)
: base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
{
this.namespaces = namespaces;
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var url = httpContext.Request.Headers["HOST"];
var index = url.IndexOf(".");
if (index < 0)
return null;
var subDomain = url.Substring(0, index);
if (subDomain == "admin")
{
var routeData = base.GetRouteData(httpContext);
if (this.namespaces != null && this.namespaces.Length > 0)
{
routeData.DataTokens["Namespaces"] = this.namespaces;
}
routeData.DataTokens["Area"] = "Admin";
routeData.DataTokens["UseNamespaceFallback"] = bool.FalseString;
return routeData;
}
return null;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
//if (true)
//{
// return base.GetVirtualPath(requestContext, values);
//}
return null;
}
}
}
2. Change Route Default in Area:
public override void RegisterArea(AreaRegistrationContext context)
{
context.Routes.Add("Admin_Default", new SubDomainRoute(
"{controller}/{action}/{id}",
new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { typeof(Controllers.HomeController).Namespace } // Namespaces defaults
));
}
3. Reference domain and subdomain to webapplication
when use this in more than one area , show error and not Run currectly
ReplyDelete