abreneliere abreneliere - 5 months ago 41
reST (reStructuredText) Question

ServiceStack: how to change member attributes in the API model at service startup?

We use ServiceStack for our Web APIs developed in C#. I would like to change the required attribute of our data members at the moment the web service starts.

Currently the required attribute is defined that way at compile time:

public string MyAttribute { get; set; }

I would like to define its value 'dynamically' when executing the AppHost.Configure.

Is there a way to achieve this with ServiceStack ? In the same manner we define routes with the Fluent api (for exemple: Routes.Add("/flight", "POST"); ) ?

I read the answer Dynamically adding attributes in ServiceStack that tell to do it in the AppHost Constructor but how to do it ?

Thank you


The question you linked provides an example in the original question. Note that if you try to add this in the Configure function of your AppHost it is probably too late. You should add it in the constructor of the AppHost. From your linked question, mythz says

For dynamically adding Service Attributes you need to add them before AppHost.Configure() since they're already initialized by the time Configure() is run, so they need to be either added in AppHost constructor or before AppHost.Init() is called.

In your case, something like this should work,

public AppHost(string serviceName, Assembly[] serviceAssemblies) : base(serviceName, serviceAssemblies)
    ApiMemberAttribute requiredAttribute = new ApiMemberAttribute {
        IsRequired = true

    Type[] requiredApiMembers = GetTypesToAddApiMemberAttributeTo();  //do whatever you need to get the types you want to add attributes to
    foreach(requiredApiMember in requiredApiMembers)