Question

I am new to ServiceStack and I am not currently familiar with the structure on how to develop a good API. I am trying to use the same Player model to do 2 separate things:

//POSTS SECTION
    [Route("/getplayernamechanged", "POST")]
    [Route("/getplayernamechanged2", "POST")] //I want to use this route to return a Player name concat with the string "just another test"
    public class Player
    {
        public string Name { get; set; }
    }

    public class PlayerResponse
    {
        public string Name { get; set; }
        public ResponseStatus ResponseStatus { get; set; }
    }

    public class PlayerService : Service
    {
        public object Any(Player request)
        {
            return new PlayerResponse { Name = request.Name+" just a test"};
        }
    }

How can I do this? Thanks

Was it helpful?

Solution

You need to define two different request objects so ServiceStack can differentiate between the two requests.

// Route 1
[Route("/getplayernamechanged", "POST")]
public class ChangePlayerNameRequest : IReturn<PlayerResponse>
{
    public string Name { get; set; }
}

// Route 2
[Route("/getplayernamechanged2", "POST")]
public class ChangePlayerNameAndConcatRequest : IReturn<PlayerResponse>
{
    public string Name { get; set; }
}

public class PlayerResponse
{
    public string Name { get; set; }
    public ResponseStatus ResponseStatus { get; set; }
}

Then you need to make separate action methods to handle each of the cases:

public class PlayerService : Service
{
    // Route 1 handled here
    public PlayerResponse Post(ChangePlayerNameRequest request)
    {
        return new PlayerResponse { Name = request.Name + " something else" };
    }

    // Route 2 handled here
    public PlayerResponse Post(ChangePlayerNameAndConcatRequest request)
    {
        return new PlayerResponse { Name = request.Name + " just a test"};
    }
}

Note I have set the return type as PlayerResponse and defined IReturn<PlayerResponse> on the DTOs. This will ensure your metadata is correct. Hope this helps, let me know if you issues in the comments.


If you want to use the same Player model for the request objects then you could extend from Player:

public class Person
{
    public string Name { get; set; }
}

// Route 1
[Route("/getplayernamechanged", "POST")]
public class ChangePlayerNameRequest : Player, IReturn<PlayerResponse>
{
}

// Route 2
[Route("/getplayernamechanged2", "POST")]
public class ChangePlayerNameAndConcatRequest : Player, IReturn<PlayerResponse>
{
}

But it is best to avoid inheritance in DTOs where possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top