我是ServiceStack的新手,我目前还不熟悉如何开发优秀的API。我试图使用相同的播放器模型来做两件事:
//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"};
}
}
我该怎么做? 感谢
答案 0 :(得分:3)
您需要定义两个不同的请求对象,以便ServiceStack可以区分这两个请求。
// 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; }
}
然后,您需要制作单独的操作方法来处理每种情况:
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"};
}
}
注意我已在DTO上将返回类型设置为PlayerResponse
并定义了IReturn<PlayerResponse>
。这将确保您的元数据正确无误。希望这有帮助,如果您在评论中发表,请告诉我。
如果您想为请求对象使用相同的Player
模型,那么您可以从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>
{
}
但最好尽可能避免在DTO中继承。