ASP.NET路由通过子MVC或API [英] ASP.NET route to mvc or api by subdomain
本文介绍了ASP.NET路由通过子MVC或API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们的应用程序有2个域(WWW | API).mydomain.com来
Our application have 2 domains (www | api).mydomain.com
我请求路由如何向api.mydomain.com到API控制器和WWW到MVC控制器?
How can I route requests to api.mydomain.com to api controllers and www to mvc controllers?
感谢您
推荐答案
我使用约束解决了我的问题。
I solved my problem using constraints.
这个网站给我的线索:<一href=\"http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx\">http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx
这是我的实现:
public class SubdomainRouteConstraint : IRouteConstraint
{
private readonly string _subdomain;
public SubdomainRouteConstraint(string subdomain)
{
_subdomain = subdomain;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.Request.Url != null && httpContext.Request.Url.Host.StartsWith(_subdomain);
}
}
和我的路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
#if !DEBUG
,constraints: new { subdomain = new SubdomainRouteConstraint("www") }
#endif
);
}
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
#if DEBUG
routeTemplate: "api/{controller}/{id}",
#else
routeTemplate: "{controller}/{id}",
#endif
defaults: new {id = RouteParameter.Optional}
#if !DEBUG
, constraints: new {subdomain = new SubdomainRouteConstraint("api")}
#endif
);
}
这篇关于ASP.NET路由通过子MVC或API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文