配置ServiceStack基本URI

时间:2012-07-13 18:58:23

标签: servicestack

我正在使用服务堆栈创建一个自托管的REST服务。 AppHostHttpListenerBase。我想为我的服务使用基本URI(例如“api”),如下所示:

http://myserver/api/service1/param
http://myserver/api/service2/param

如果没有在每条路线中定义“api”,我该怎么做。在IIS中,我可以设置一个虚拟目录来隔离服务,但是如何在自托管时执行此操作?

4 个答案:

答案 0 :(得分:4)

这里你去..(作为奖励,这就是你将服务放入插件的方式。

using BlogEngineService;
using ServiceStack.WebHost.Endpoints;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogEngineWinService
{
    public class AppHost : AppHostHttpListenerBase
    {
        public AppHost() : base("Self Host Service", typeof(AppHost).Assembly) { }
        public override void Configure(Funq.Container container)
        {
            Plugins.Add(new BlogEngine());
        }
    }
}

这是你自动装配的方式

通话appHost.Routes.AddFromAssembly2(typeof(HelloService).Assembly);是将分机称为自动接线。

using ServiceStack.WebHost.Endpoints;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.ServiceInterface;

namespace BlogEngineService
{
    public class BlogEngine : IPlugin, IPreInitPlugin
    {
        public void Register(IAppHost appHost)
        {

            appHost.RegisterService<HelloService>();
            appHost.Routes.AddFromAssembly2(typeof(HelloService).Assembly);
        }

        public void Configure(IAppHost appHost)
        {

        }
    }
}

这就是您如何标记服务类以为其指定前缀。 只需使用此属性标记类

using ServiceStack.DataAnnotations;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogEngineService
{
    public class Hello
    {
        [PrimaryKey]
        public string Bob { get; set; }
    }

    public class HelloResponse
    {
        public string Result { get; set; }
    }

    [PrefixedRoute("/test")]
    public class HelloService : Service
    {

        public object Any(Hello request)
        {
            return new HelloResponse { Result = "Hello, " + request.Bob};
        }
    }
}

在项目中为扩展程序创建一个CS文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using ServiceStack.Common;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.Text;
using ServiceStack.ServiceHost;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.ServiceInterface;

namespace ServiceStack.ServiceInterface
{
    public static class ServiceRoutesExtensions
    {
        /// <summary>
        ///     Scans the supplied Assemblies to infer REST paths and HTTP verbs.
        /// </summary>
        ///<param name="routes">The <see cref="IServiceRoutes"/> instance.</param>
        ///<param name="assembliesWithServices">
        ///     The assemblies with REST services.
        /// </param>
        /// <returns>The same <see cref="IServiceRoutes"/> instance;
        ///     never <see langword="null"/>.</returns>
        public static IServiceRoutes AddFromAssembly2(this IServiceRoutes routes,
                                                     params Assembly[] assembliesWithServices)
        {
            foreach (Assembly assembly in assembliesWithServices)
            {

                AddNewApiRoutes(routes, assembly);
            }

            return routes;
        }

        private static void AddNewApiRoutes(IServiceRoutes routes, Assembly assembly)
        {
            var services = assembly.GetExportedTypes()
                .Where(t => !t.IsAbstract
                            && t.HasInterface(typeof(IService)));

            foreach (Type service in services)
            {
                var allServiceActions = service.GetActions();
                foreach (var requestDtoActions in allServiceActions.GroupBy(x => x.GetParameters()[0].ParameterType))
                {
                    var requestType = requestDtoActions.Key;
                    var hasWildcard = requestDtoActions.Any(x => x.Name.EqualsIgnoreCase(ActionContext.AnyAction));
                    string allowedVerbs = null; //null == All Routes
                    if (!hasWildcard)
                    {
                        var allowedMethods = new List<string>();
                        foreach (var action in requestDtoActions)
                        {
                            allowedMethods.Add(action.Name.ToUpper());
                        }

                        if (allowedMethods.Count == 0) continue;
                        allowedVerbs = string.Join(" ", allowedMethods.ToArray());
                    }
                    if (service.HasAttribute<PrefixedRouteAttribute>())
                    {
                        string prefix = "";
                        PrefixedRouteAttribute a = (PrefixedRouteAttribute)Attribute.GetCustomAttribute(service, typeof(PrefixedRouteAttribute));
                        if (a.HasPrefix())
                        {
                            prefix = a.GetPrefix();
                        }
                        routes.AddRoute(requestType, allowedVerbs, prefix);
                    }
                    else
                    {
                        routes.AddRoute(requestType, allowedVerbs);
                    }
                }
            }
        }

        private static void AddRoute(this IServiceRoutes routes, Type requestType, string allowedVerbs, string prefix = "")
        {
            var newRoutes = new ServiceStack.ServiceHost.ServiceRoutes();
            foreach (var strategy in EndpointHost.Config.RouteNamingConventions)
            {
                strategy(newRoutes, requestType, allowedVerbs);
            }
            foreach (var item in newRoutes.RestPaths)
            {

                string path = item.Path;
                if (!string.IsNullOrWhiteSpace(prefix))
                {
                    path = prefix + path;
                }
                routes.Add(requestType, restPath: path, verbs: allowedVerbs);
            }
        }
    }

    public class PrefixedRouteAttribute : Attribute
    {
        private string _prefix { get; set; }
        private bool _hasPrefix { get; set; }

        public PrefixedRouteAttribute(string path) 
        {
            if (!string.IsNullOrWhiteSpace(path))
            {
                this._hasPrefix = true;
                this._prefix = path;
                //this.Path = string.Format("/{0}{1}", Prefix, Path);
            }
        }
        public bool HasPrefix()
        {
            return this._hasPrefix;
        }
        public string GetPrefix()
        {
            return this._prefix;
        }
    }
}

答案 1 :(得分:2)

ServiceStack's HttpListener hosts期望托管一个根/路径,因为正常的用例是让每个自托管服务在不同的自定义端口上可用。

由于它目前不支持在/ custompath中托管,因此您必须在所有服务路由上指定/api/前缀。

Add an issue如果您希望获得对自定义路径托管的支持。

答案 2 :(得分:2)

实际上有一个更简单的解决方案。在您的web.config中,将您的http-handler更新为:

<httpHandlers>
  <add path="api*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>

有了上述内容,您的所有服务apis都必须以“/ api /”作为前缀。如果您已在任何路线中使用过“/ api /”,则现在必须将其删除或在通话中指定两次。

参考: https://github.com/ServiceStack/SocialBootstrapApi

答案 3 :(得分:1)

我找到了解决方法。我只在自托管下测试了这个。

创建一个继承自RouteAttribute

的'PrefixedRouteAttribute'类
public class PrefixedRouteAttribute : RouteAttribute
{
  public static string Prefix { get; set; }

  public PrefixedRouteAttribute(string path) :
    base(path)
  {
    SetPrefix();
  }

  public PrefixedRouteAttribute(string path, string verbs)
    : base(path, verbs)
  {
    SetPrefix();
  }

  private void SetPrefix()
  {
    if (!string.IsNullOrWhiteSpace(Prefix))
    {
      this.Path = string.Format("/{0}{1}", Prefix, Path);
    }
  }   
}

创建AppHost时,您可以设置前缀

PrefixedRouteAttribute.Prefix = "api";

然后,不使用[Route]属性,而是使用类上的[PrefixRoute]属性

[PrefixedRoute("/echo")]
[PrefixedRoute("/echo/{Value*}")]
public class Echo
{
  [DataMember]
  public string Value { get; set; }
}

这将适用于

的请求
/api/echo
/api/echo/1

这可能会有所改善。我真的不喜欢我需要通过静态属性设置前缀,但我想不出在我的设置下更好的方法。创建覆盖属性的原则似乎是合理的,这是重要的部分。