Simple URL routes in WCF Rest 4.0 without trailing slash

后端 未结 7 1442
太阳男子
太阳男子 2021-02-01 20:27

I have a WCF REST 4.0 project based on the the WCF REST Service Template 40(CS). I\'d like to expose simple service endpoint URLs without trailing slashes. For example:

7条回答
  •  猫巷女王i
    2021-02-01 21:16

    A bit more reusable:

    public class Global : NinjectHttpApplication
    {
    
        protected override void OnApplicationStarted()
        {
            base.OnApplicationStarted();
            RegisterRoutes();
        }
    
        private void RegisterRoutes()
        {
            RouteTable.Routes.Add(new ServiceRoute("login", new NinjectWebServiceHostFactory(), typeof(LoginService)));
            RouteTable.Routes.Add(new ServiceRoute("incidents", new NinjectWebServiceHostFactory(), typeof(IncidentService)));
            SetRoutePrefixes();
        }
        //This is a workaround for WCF forcing you to end with "/" if you dont have a urlTemplate and redirecting if you dont have
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string rawUrl = HttpContext.Current.Request.RawUrl.ToLower();
    
    
            if (_routePrefixes.Any(rawUrl.EndsWith))
            {
                HttpContext.Current.RewritePath(rawUrl + "/");  // append trailing slash
            }
        }
    
    
        private static List _routePrefixes; 
        private static void SetRoutePrefixes()
        {
            _routePrefixes = new List();
            foreach (var route in RouteTable.Routes)
            {
                var r = route as Route;
                var routePrefix = r.Url.Split('/').First();
                _routePrefixes.Add(routePrefix);
            }
        }
    

提交回复
热议问题