如何让ServiceStack在MVC4项目中工作?

本文关键字:项目 工作 MVC4 ServiceStack | 更新日期: 2023-09-27 18:11:40

我创建了一个新的MVC 4项目,并从NuGet更新了所有需要的ServiceStack包。

我把这个添加到我的Web.config:

<location path="ss">
  <system.web>
    <!-- httpHandlers added for ServiceStack, this will work for IIS6 and Below -->
    <httpHandlers>
      <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*"/>
    </httpHandlers>
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <add name="ServiceStack.Factory" path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true"/>
    </handlers>
  </system.webServer>
</location>

My AppHost:

namespace MySql_Test.App_Start
{
    public class ApplicationHost : AppHostHttpListenerBase
    {
        public ApplicationHost()
            : base("PersonService", typeof(PersonService).Assembly)
        {
        }
        public override void Configure(Funq.Container container)
        {
            SetConfig(new HostConfig { HandlerFactoryPath = "ss" });
            container.Register<IDbConnectionFactory>(
                new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["DuDealsConnStr"].ConnectionString,
                    ServiceStack.OrmLite.MySql.MySqlDialectProvider.Instance));
        }
    }
    public class PersonService : Service
    {
    }
}

My Global.cs:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        (new ApplicationHost()).Init();
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

当我构建并运行项目并尝试导航到localhost/ss/metadata时它一直给我一个404页面

如何让ServiceStack在MVC4项目中工作?

MVC4项目默认使用WebApi。您需要阻止WebApi注册以接收您希望ServiceStack处理的请求。

参见ServiceStack文档,创建你的第一个webservice指令:

从默认的MVC4 VS.NET模板中禁用WebApi
如果你正在使用MVC4,那么你需要在global.asax.cs中注释行来禁用WebApi

//WebApiConfig.Register(GlobalConfiguration.Configuration);

Application_Start设置为:

protected void Application_Start()
{
    (new ApplicationHost()).Init();
}

如果你想让ServiceStack与WebApi一起工作,那么你需要告诉WebApi不要处理以你的ss/路径开始的请求:

protected void Application_Start()
{
    (new ApplicationHost()).Init();
    AreaRegistration.RegisterAllAreas();
    // Ignore ServiceStack routes
    RouteTable.Routes.IgnoreRoute("ss/{*pathInfo}");
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

希望对你有帮助。