Domain-based routing in ASP.NET Core 2.0

后端 未结 3 1834
梦如初夏
梦如初夏 2020-12-03 04:27

I have an ASP.NET Core 2.0 app hosted on an Azure App Service.

This application is bound to domainA.com. I have one route in my app—for example, d

3条回答
  •  醉话见心
    2020-12-03 04:46

    For .net Core MVC, you can create a new IRouteConstraint and a RouteAttribute

    => IRouteConstraint.cs

    using System;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    
    namespace Microsoft.AspNetCore.Routing
    {
        public class ConstraintHost : IRouteConstraint
        {
    
            public string _value { get; private set; }
            public ConstraintHost(string value)
            {
                _value = value;
            }
    
            public bool Match(HttpContext httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                string hostURL = httpContext.Request.Host.ToString();
                if (hostURL == _value)
                {
                    return true;
                }
                //}
                return false;
                //return hostURL.IndexOf(_value, StringComparison.OrdinalIgnoreCase) >= 0;
            }
    
            public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
            {
                throw new NotImplementedException();
            }
        }
        public class ConstraintHostRouteAttribute : RouteAttribute
        {
            public ConstraintHostRouteAttribute(string template, string sitePermitted)
                : base(template)
            {
                SitePermitted = sitePermitted;
            }
    
            public RouteValueDictionary Constraints
            {
                get
                {
                    var constraints = new RouteValueDictionary();
                    constraints.Add("host", new ConstraintHost(SitePermitted));
                    return constraints;
                }
            }
    
            public string SitePermitted
            {
                get;
                private set;
            }
        }
    } 
    

    And in your Controller can use it like that:

        [ConstraintHostRoute("myroute1/xxx", "domaina.com")]
        [ConstraintHostRoute("myroute2/yyy", "domainb.com")]
        public async Task MyController()
        {
          return View();
        }
    

提交回复
热议问题