Merwer
Merwer

Reputation: 546

Adding Parameters to ServiceStack's base path

Is there a way to add a route parameter to the base factory path in ServiceStack? Currently, we configure IIS to route any requests starting with /api/ to the ServiceStackHttpHandlerFactory through the web.config.

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

  <!-- Required for IIS 7.0 -->
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
    </handlers>
  </system.webServer>

In addition, we tell the ServiceStack application that it has a base factory path of api through the endpoint host config in AppHost.cs

SetConfig(new EndpointHostConfig { ServiceStackHandlerFactoryPath = "api" });

Once this is done, we specify the routes to our services through the [Route] attribute on our request DTOs, and we don't have to worry about the '/api' part.

Is there a way to add a global parameter to the path's route? The idea would be to add this parameter in the config /api/{Locale} and then all of our request DTOs would inherit from a BaseRequest class with a property string Locale {get;set;}.

As an added bonus, if it was possible to make this an optional parameter (likely through two routes in web.config & AppHost.cs) to allow for a 'default' value of this parameter that'd be even better.


EDIT

I'm currently exploring the idea of creating a class extending the RouteAttribute class.

public class PrefixedRouteAttribute : RouteAttribute
{
  public static string Prefix = string.Empty;
  public PrefixedRouteAttribute(string path) : base(Prefix + path)
  public PrefixedRouteAttribute(string path, string verbs) : base(Prefix + path, verbs)
}

The Prefix value can be set in AppHost.cs to /{Locale}, which will automatically inject the Locale parameter into all routes, provided I use [PrefixedRoute] instead of [Route].

This approach seems to be working, except I don't see a way to make the {Locale} optional.

Upvotes: 2

Views: 403

Answers (1)

Amir Abiri
Amir Abiri

Reputation: 9437

This should work:

public abstract class BaseDto
{
    public string Locale { get; set; }

    public BaseDto()
    {
        Locale = "en";
    }
}

[Route("/{Locale*}/test")]
public class TestDto : BaseDto
{
    public int SomeParam { get; set; }
}

public class TestService : Service
{
    public Result Get(TestDto request)
    {
        ...
    }
}

Upvotes: 2

Related Questions