Skip to content
Demis Bellot edited this page Apr 2, 2014 · 16 revisions

Add ServiceStack to an existing MVC Project

You can easily add ServiceStack to any ASP.NET MVC project by getting it from NuGet with:

PM> Install-Package ServiceStack.Mvc

This install ServiceStack with additional (and optional) integration support for MVC letting you use ServiceStack's IOC to initialize MVC controllers or create MVC Controllers with built-in access to ServiceStack's components.

Enabling ServiceStack in Web.Config

Typically when hosting ServiceStack with MVC you'd want to host it at the /api custom route which you can do by adding the IIS7+ configuration below to your Web.config:

<location path="api">
  <system.web>
    <httpHandlers>
      <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*"/>
    </httpHandlers>
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add path="*" name="ServiceStack.Factory" 
           type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" 
           preCondition="integratedMode" 
           resourceType="Unspecified" allowPathInfo="true" />
    </handlers>
  </system.webServer>
</location>

See Run Side-by-Side with another web framework for other web.config examples of hosting ServiceStack, e.g with IIS6/Mono.

Inferring ServiceStack's HandlerFactoryPath (/api)

Whilst ServiceStack automatically tries to infer the handler path based on the <location> tag, if there's an uncommon Web.config setup or there are some other issue inferring it, it' recommended to also explicitly set the /api handler path in Config.HandlerFactoryPath, e.g:

SetConfig(new HostConfig { 
    HandlerFactoryPath = "api",
});

Initializing ServiceStack

Hosting in ASP.NET MVC is very similar to hosting in any ASP.NET framework, i.e. The ServiceStack AppHost still needs to be initialized on start up in your Global.asax.cs (or WebActivator), e.g:

public class Global : System.Web.HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        new AppHost().Init();
    }
}

You MUST also register ServiceStacks /api path by adding the lines below to MvcApplication.RegisterRoutes(RouteCollection) in the Global.asax:

routes.IgnoreRoute("api/{*pathInfo}"); 
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" }); 

Place them before the current entries the method.

Removing Web API

For MVC applications that include WebApi, you would need to unregister it by commenting out this line:

//WebApiConfig.Register(GlobalConfiguration.Configuration);

Optional Configuration

Sharing dependencies with MVC Controllers

To register all your dependencies in your ServiceStack AppHost, register an MVC Controller factory so both your MVC Controllers and ServiceStack services get auto-wired with these dependencies in your AppHost.Configure(), e.g:

void Configure(Funq.Container container) 
{
    //Set MVC to use the same Funq IOC as ServiceStack
    ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
}

Calling ServiceStack Services from MVC Controllers

Just like in ServiceStack, you can retrieve an auto-wired Service and execute it using HostContext.ResolveService<TService>(), e.g:

public HelloController : ServiceStackController 
{
    public void Index(string name) 
    {
        using (var hello = HostContext.ResolveService<HelloService>(base.HttpContext))
        {
           ViewBag.GreetResult = hello.Get(name).Result;
           return View();
        }
    }        
}

Another cleaner way to share functionality between MVC and ServiceStack is to get them both injected with a shared dependency. See the IGreeter example on StackOverflow.

Adding Mini Profiler

To enable the Mini Profiler add the following lines in to MvcApplication in Global.asax.cs:

protected void Application_BeginRequest(object src, EventArgs e)
{
    if (Request.IsLocal)
        ServiceStack.MiniProfiler.Profiler.Start();
}

protected void Application_EndRequest(object src, EventArgs e)
{
    ServiceStack.MiniProfiler.Profiler.Stop();
}

For more info on the MiniProfiler see the Built in profiling wiki.

The Urls for metadata page and included Services:



  1. Getting Started
    1. Create your first webservice
    2. Your first webservice explained
    3. ServiceStack's new API Design
    4. Designing a REST-ful service with ServiceStack
    5. Example Projects Overview
  2. Reference
    1. Order of Operations
    2. The IoC container
    3. Metadata page
    4. Rest, SOAP & default endpoints
    5. SOAP support
    6. Routing
    7. Service return types
    8. Customize HTTP Responses
    9. Plugins
    10. Validation
    11. Error Handling
    12. Security
    13. Debugging
  3. Clients
    1. Overview
    2. C# client
    3. Silverlight client
    4. JavaScript client
    5. Dart Client
    6. MQ Clients
  4. Formats
    1. Overview
    2. JSON/JSV and XML
    3. ServiceStack's new HTML5 Report Format
    4. ServiceStack's new CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  5. View Engines 4. Razor & Markdown Razor
    1. Markdown Razor
  6. Hosts
    1. IIS
    2. Self-hosting
    3. Messaging
    4. Mono
  7. Security
    1. Authentication/authorization
    2. Sessions
    3. Restricting Services
  8. Advanced
    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in caching options
    9. Built-in profiling
    10. Form Hijacking Prevention
    11. Auto-Mapping
    12. HTTP Utils
    13. Virtual File System
    14. Config API
    15. Physical Project Structure
    16. Modularizing Services
    17. MVC Integration
  9. Plugins 3. Request logger 4. Swagger API
  10. Tests
    1. Testing
    2. HowTo write unit/integration tests
  11. Other Languages
    1. FSharp
    2. VB.NET
  12. Use Cases
    1. Single Page Apps
    2. Azure
    3. Logging
    4. Bundling and Minification
    5. NHibernate
  13. Performance
    1. Real world performance
  14. How To
    1. Sending stream to ServiceStack
    2. Setting UserAgent in ServiceStack JsonServiceClient
    3. ServiceStack adding to allowed file extensions
    4. Default web service page how to
  15. Future
    1. Roadmap

Clone this wiki locally