我第一次在一个以 ASP.NET MVC 开始的全新项目中使用 ServiceStack。我在根目录托管 ServiceStack API,所以我的 web.config 如下所示:
  <system.web>
    <httpHandlers>
      <add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
    </httpHandlers>
  </system.web>
  <system.webServer>
    <handlers>
      <add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
    </handlers>
  </system.webServer>
和我的 App_Start/RouteConfig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("*");
}
这是我的服务:
[Route("/catalogs/{ID}")]
[DataContract]
public class CatalogRequest : IReturn<Catalog>
{
    [DataMember]
    public int ID { get; set; }
}
[DefaultView("Catalogs")]
public class CatalogService : Service
{
    public object Get(CatalogRequest request)
    {
        return (request.ID == 9999) ? new Catalog() { ID = 9999 } : null;
    }
}
我使用以下内容进行测试:
public class TestAppHost : AppHostHttpListenerBase
{
    public TestAppHost() : base("TestService", typeof(TestAppHost).Assembly) { }
    public override void Configure(Funq.Container container)
    {
        IoC.Configure(container); // IoC is where all Funq configuration is done
    }
}
在我的 VisualStudio 单元测试中,我像这样启动 AppHost:
[TestClass]
public class TestHelper
{
    public const string TEST_HOST_URL = "http://127.0.0.1:8888/";
    private static TestAppHost __AppHost;
    [AssemblyInitialize]
    public static void Initialize(TestContext context)
    {
        // Start the test app host.
        __AppHost = new TestAppHost();
        __AppHost.Init();
        __AppHost.Start(TEST_HOST_URL);
    }
    [AssemblyCleanup]
    public static void Cleanup()
    {
        __AppHost.Dispose();
        __AppHost = null;
    }
}
当我运行测试时:
[TestMethod]
public void RequestCatalogByID()
{
    var client = new JsonServiceClient(TestHelper.TEST_HOST_URL);
    var request = new CatalogRequest() { ID = 9999 };
    var response = client.Get(request);
    Assert.IsNotNull(response);
}
即使 URL 似乎正确,我也会收到“未找到”异常:http://127.0.0.1:8888/catalogs/9999.
将浏览器指向http://127.0.0.1:8888/metadata显示没有操作的元数据页面。
我究竟做错了什么?