Skip to content

Plugins

Demis Bellot edited this page · 37 revisions

  1. Getting Started

    1. Creating your first project
      1. Create Service from scratch
    2. Your first webservice explained
    3. ServiceStack's new API Design
    4. Designing a REST-ful service with ServiceStack
    5. Example Projects Overview
    6. Learning Resources
  2. Reference

    1. Order of Operations
    2. The IoC container
    3. Configuration and AppSettings
    4. Metadata page
    5. Rest, SOAP & default endpoints
    6. SOAP support
    7. Routing
    8. Service return types
    9. Customize HTTP Responses
    10. Plugins
    11. Validation
    12. Error Handling
    13. Security
    14. Debugging
    15. JavaScript Client Library (ss-utils.js)
  3. Clients

    1. Overview
    2. C#/.NET client
    3. Add ServiceStack Reference
      1. C# Add Reference
      2. F# Add Reference
      3. VB.NET Add Reference
      4. Swift Add Reference
      5. Java Add Reference
    4. Silverlight client
    5. JavaScript client
      1. Add TypeScript Reference
    6. Dart Client
    7. 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

    1. Razor & Markdown Razor
    2. Markdown Razor
  6. Hosts

    1. IIS
    2. Self-hosting
    3. Messaging
    4. Mono
  7. Security

    1. Authentication/authorization
    2. Sessions
    3. Restricting Services
    4. Encrypted Messaging
  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
    18. ServiceStack Integration
    19. Embedded Native Desktop Apps
    20. Auto Batched Requests
    21. Versioning
  9. Server Events

    1. Overview
    2. JavaScript Client
    3. C# Server Events Client
    4. Redis Server Events
  10. Encrypted Messaging

    1. Overview
    2. Encrypted Client
  11. Plugins

    1. Auto Query
    2. Server Sent Events
    3. Swagger API
    4. Postman
    5. Request logger
    6. Sitemaps
    7. Cancellable Requests
    8. CorsFeature
  12. Tests

    1. Testing
    2. HowTo write unit/integration tests
  13. ServiceStackVS

    1. Install ServiceStackVS
    2. Add ServiceStack Reference
    3. AngularJS App Template
    4. ReactJS App Template
  14. Other Languages

    1. FSharp
      1. Add ServiceStack Reference
    2. VB.NET
      1. Add ServiceStack Reference
    3. Swift
      1. Swift Add Reference
    4. Java
      1. Add ServiceStack Reference
      2. Android Studio & IntelliJ
      3. Eclipse
  15. Amazon Web Services

    1. ServiceStack.Aws
    2. PocoDynamo
    3. AWS Live Demos
    4. Getting Started with AWS
  16. Deployment

    1. Deploy Multiple Sites to single AWS Instance
      1. Simple Deployments to AWS with WebDeploy
    2. Advanced Deployments with OctopusDeploy
  17. Install 3rd Party Products

    1. Redis on Windows
    2. RabbitMQ on Windows
  18. Use Cases

    1. Single Page Apps
      1. HTML, CSS and JS Minifiers
    2. Azure
      1. Connecting to Azure Redis via SSL
    3. Logging
    4. Bundling and Minification
    5. NHibernate
  19. Performance

    1. Real world performance
  20. Other Products

    1. ServiceStack.Redis
    2. ServiceStack.OrmLite
    3. ServiceStack.Text
  21. Future

    1. Roadmap
Clone this wiki locally

ServiceStack Plugin API provides a declarative way to enable modular functionality in ServiceStack:

Plugin API

public interface IPlugin
{
    void Register(IAppHost appHost);
}

Custom Logic before Plugins are loaded

If your plugin also implements IPreInitPlugin it will get run before any plugins are registered:

public interface IPreInitPlugin
{
    void Configure(IAppHost appHost);
}

Custom Logic after Plugins are loaded

If your plugin implements IPostInitPlugin it will get run after all plugins are registered:

public interface IPostInitPlugin
{
    void AfterPluginsLoaded(IAppHost appHost);
}

Disabling Plugins via Feature Enum Flags

All built-in Plugins are Registered and available via base.Plugins before your Configure() script is run so you have a chance to modify the behaviour or remove un-used plugins which is exactly what the short-hand:

SetConfig(new HostConfig { 
    EnableFeatures = Feature.All.Remove(Feature.Csv)
});

Which under the covers just does:

if ((Feature.Csv & config.EnableFeatures) != Feature.Csv)
    Plugins.RemoveAll(x => x is CsvFormat);

Which you now also have an opportunity to also do in your AppHost Configure() start-up script yourself - if you want to remove or customize any pre-loaded plugins.

Resolving Plugins

You can easily use LINQ to fetch any specific plugin:

var htmlFormat = base.Plugins.First(x => x is HtmlFormat) as HtmlFormat;

Which is also what the this.GetPlugin<T>() convenience extension method does:

var htmlFormat = base.GetPlugin<HtmlFormat>();

List of Plugins added by Default

A list of all of the plugins available on ServiceStack and how to add them:

Auto-registered plugins

These plugins below are already added by default, you can remove or customize them using the methods described above.

Metadata Feature

Provides ServiceStack's auto-generated metadata pages.

var feature = Plugins.FirstOrDefault(x => x is MetadataFeature); 
Plugins.RemoveAll(x => x is MetadataFeature); 

Predefined Routes

Provides ServiceStack's pre-defined routes used in the built-in C# Service Clients.

var feature = Plugins.FirstOrDefault(x => x is PredefinedRoutesFeature); 
Plugins.RemoveAll(x => x is PredefinedRoutesFeature); 

Request Info

Provides ServiceStack's Request Info feature useful for debugging requests. Just add ?debug=requestinfo in your /pathinfo and ServiceStack will return a dump of all the HTTP Request parameters to help with with debugging interoperability issues. The RequestInfoFeature is only enabled for Debug builds.

var feature = Plugins.FirstOrDefault(x => x is RequestInfoFeature); 
Plugins.RemoveAll(x => x is RequestInfoFeature); 

CSV Format

Providing ServiceStack's CSV Format.

var feature = Plugins.FirstOrDefault(x => x is CsvFormat); 
Plugins.RemoveAll(x => x is CsvFormat); 

Note: By default the CSV Format tries serialize the Response object directly into CSV which is only ideal if your responses return List<Poco>. If however you mark your Response DTO with the [Csv(CsvBehavior.FirstEnumerable)] attribute the CSV Format instead will only serialize the first IEnumerable<T> it finds on your Response DTO e.g. if you had a List<Poco> Results property it will only serialize this list in the tabular CSV Format which is typically the behaviour you want.

Html Format

Providing ServiceStack's Html Format.

var feature = Plugins.FirstOrDefault(x => x is HtmlFormat); 
Plugins.RemoveAll(x => x is HtmlFormat); 

Razor Markdown Format

This provides ServiceStack's Razor Markdown Format and also enables ServiceStack to serve static .md or .markdown files in either plain text, rendered as HTML (partial), or rendered in HTML inside a static _Layout.shtml HTML template.

var feature = Plugins.FirstOrDefault(x => x is MarkdownFormat); 
Plugins.RemoveAll(x => x is MarkdownFormat); 

The entire docs.servicestack.net website is rendered using static Markdown. More information of Razor Markdown features can be found in:

Available Plugins

The rest of ServiceStack's plugins are not enabled by default by can easily be added on adhoc basis, as and when needed.

Auto Query

AutoQuery enables instant querying support on RDBMS tables behind clean self-describing APIs by enhancing the ideal API the developer would naturally write and completing their implementation for them! This is essentially the philosophy behind AutoQuery which utilizes conventions to automate creation of intent-based self-descriptive APIs that are able to specify configurable conventions and leverage extensibility options to maximize the utility of AutoQuery services.

Plugins.Add(new AutoQueryFeature { MaxLimit = 100 });

Requires ServiceStack.Server

Server Events

Server Events enables server push notifications to create real-time responsive web apps with its support for Server Sent Events. It offers a number of different API's for sending notifications to select users at different levels of granularity, letting you interact and modify live-running web apps.

Plugins.Add(new ServerEventsFeature());

Postman

The Postman Rest Client is a very popular and easy to use HTTP Request composer that makes it easy to call web services, similar to Fiddler's Composer. It also provides as an alternative for auto-generating API documentation to ServiceStack's Swagger support that makes it easier to call existing services but does require users to install the Postman Rest Client.

Plugins.Add(new PostmanFeature());
Plugins.Add(new CorsFeature());

Swagger support

Swagger support an optional add-on available in the ServiceStack.Api.Swagger NuGet package.

After installing the NuGet package enable the Swagger with:

Plugins.Add(new SwaggerFeature());

Now you can enjoy your shiny new Swagger UI at: http://yoursite/swagger-ui/index.html

Annotating your services

You can further document your services in the Swagger UI with the new [Api] and [ApiMember] annotation attributes, e,g: Here's an example of a fully documented service:

[Api("Service Description")]
[Route("/swagger/{Name}", "GET", Summary = @"GET Summary", Notes = "GET Notes")]
[Route("/swagger/{Name}", "POST", Summary = @"POST Summary", Notes = "POST Notes")]
public class MyRequestDto
{
    [ApiMember(Name="Name", Description = "Name Description", 
               ParameterType = "path", DataType = "string", IsRequired = true)]
    public string Name { get; set; }
}

Razor Format

Provides ServiceStack's primary HTML story with support for the MVC Razor view engine.

Plugins.Add(new RazorFormat()); 

It's an optional .NET 4.0 plugin that is available in the ServiceStack.Razor NuGet package.

Validation

Enable the validation feature if you want to ensure all of ServiceStack's Fluent validators for Request DTOs IValidator<TRequestDto> are automatically validated on every request.

Plugins.Add(new ValidationFeature());

More information on ServiceStack's built-in Fluent Validation support is described on the Validation page.

Authentication

The Authentication Feature enables the Authentication and Authorization support in ServiceStack. It makes available the AuthService at the default route at /auth/{provider}, registers AssignRoles and UnAssignRoles services (at /assignroles and /unassignroles default routes) and auto-enables Session support if it's not added already.

An example AuthFeature registration (taken from the SocialBootstrapApi project):

Plugins.Add(new AuthFeature(
    () => new CustomUserSession(), //Use your own typed Custom UserSession type
    new IAuthProvider[] {
        new CredentialsAuthProvider(),         //HTML Form post of UserName/Password credentials
        new TwitterAuthProvider(appSettings),  //Sign-in with Twitter
        new FacebookAuthProvider(appSettings), //Sign-in with Facebook
        new BasicAuthProvider(),               //Sign-in with Basic Auth
    }));

This registers and provides your ServiceStack host a myriad of different Authentication options as described above.

Session support

If you're not using the AuthFeature above and you still want Session support you need to enable it explicitly with:

Plugins.Add(new SessionFeature());

This will add a Request Filter to instruct any HTTP client calling a ServiceStack web service to create a Temporary (ss-id) and Permanent (ss-pid) cookie if not already done so.

Registration

Related to Authentication is Registration which enables the Registration Service at the default route /register which lets new Users to be registered and validated with the Credentials and Basic AuthProviders.

Plugins.Add(new RegistrationFeature());

See the SocialBootstrapApi project for a working example of Registration and Authentication.

MessagePack format

To add fast binary MessagePack support to ServiceStack install the ServiceStack.Plugins.MsgPack NuGet package and register the plugin with:

Plugins.Add(new MsgPackFormat());

ProtoBuf format

To enable ProtoBuf support install the ServiceStack.Plugins.ProtoBuf NuGet package and register the plugin with:

Plugins.Add(new ProtoBufFormat());

Request Logger

Add an In-Memory IRequestLogger and service with the default route at /requestlogs which maintains a live log of the most recent requests (and their responses). Supports multiple config options incl. Rolling-size capacity, error and session tracking, hidden request bodies for sensitive services, etc.

Plugins.Add(new RequestLogsFeature());

The IRequestLogger is a great way to introspect and analyze your service requests in real-time. Here's a screenshot from the http://bootstrapapi.servicestack.net website:

Live Screenshot

It supports multiple queryString filters and switches so you filter out related requests for better analysis and debuggability:

Request Logs Usage

The RequestLogsService is just a simple C# service under-the-hood but is a good example of how a little bit of code can provide a lot of value in ServiceStack's by leveraging its generic, built-in features.

Web Sudo

A common UX in some websites is to add an extra layer of protection for super protected functionality by getting users to re-confirm their password verifying it's still them using the website, common in places like confirming a financial transaction.

WebSudo is a new feature similar in spirit requiring users to re-authenticate when accessing Services annotated with the [WebSudoRequired] attribute. To make use of WebSudo, first register the plugin:

Plugins.Add(new WebSudoFeature());

You can then apply WebSudo behavior to existing services by annotating them with [WebSudoRequired]:

[WebSudoRequired]
public class RequiresWebSudoService : Service
{
    public object Any(RequiresWebSudo request)
    {
        return request;
    }
}

Once enabled this will throw a 402 Web Sudo Required HTTP Error the first time the service is called:

var requiresWebSudo = new RequiresWebSudo { Name = "test" };
try
{
    client.Send<RequiresWebSudoResponse>(requiresWebSudo); //throws
}
catch (WebServiceException)
{
    client.Send(authRequest); //re-authenticate
    var response = client.Send(requiresWebSudo); //success!
}

Re-authenticating afterwards will allow access to the WebSudo service.

Community Resources

Something went wrong with that request. Please try again.