Populate a JSON POST Request on a dto or any object?

Is there anything that can do something like Request.FromJson<MyDto>() that can take a json post and populate the data into any arbitrary dto?

Similar to Request.GetFlattenedRequestParams() but an object from the json data posted (e.g. not FormData and not QueryString data)

The normal Request dto would still be populated, so in other words…

// pseudo code
public class MyService : Service {

  public async Task<MyPostRequest> Post(MyPostRequest request) {
    // this is what I want to be able to do from a JSON Post
    // request is still filled, but want to populate another dto from the json post request
    var otherDto = Request.FromJson<MyDto>();

    // Can't do the following as it's a JSON post and not a Form / QueryString post
    var reqParams = Request.GetFlattenedRequestParams();
    var typeDeserializer = new StringMapTypeDeserializer(typeof(MyDto));
    var otherDtoFromForm = typeDeserializer.PopulateFromMap(typeof(MyDto).CreateInstance(), reqParams) as MyDto;

I have a SPA and the default is to post JSON data.

However in one particular Request (a custom CredentialsAuthProvider) the default Authenticate request dto doesn’t have all the custom fields.

Normally I would Request.GetFlattenedRequestParams() and StringMapTypeDeserializer.PopulateFromMap(), but GetFlattenedRequestParams() only works on FormData/QueryString and I need something to populate from the JSON data instead.

Now, I did get a workaround by changing the SPA on that particular request to use the Javascript FormData() and post it like a form to get it to work, so if there isn’t a solution, that is ok, but it’s a little tedious working with FormData() and the params will change in the future, so a Javascript object would work better than FormData(). Also it would help to keep everything consistent with all the other requests as this was slightly hacked together to get it to work with FormData() instead of JSON.

I don’t understand if you just want to deserialize the DTO you’d just use the JSON Serializer. But the Request is a forward only stream which you need to buffer then you can re-read the JSON from the Reqeust body, then just use the JSON Serializer to deserialize it, e.g:

var json = await Request.GetRawBodyAsync(); 
var dto = json.FromJson<Dto>();

Yeah that is what I want to do, but not sure if it’s worth the buffer changes if it affects performance on all requests.

var json = await Request.GetRawBodyAsync(); 
var dto = json.FromJson<Dto>();

You said you wanted the Request populated so ServiceStack has to read and deserialize the Request Body. If you want ServiceStack to skip serializing a specific request you can have your Request DTO implement IRequiresRequestStream so you can read from the unread Reqeust InputStream yourself.

Otherwise in your pre-request filter you can inspect the incoming IRequest and only selectively buffer the requests you want.