shawhu
shawhu

Reputation: 1237

How do I get raw request body using servicestack with content-type set to application/x-www-form-urlencoded?

I have my DTO

Route("/testing","POST")]
public class TestingRequest:IRequiresRequestStream
{
    public Stream RequestStream { get; set; }
}

and my service

public async Task<object> Post(TestingRequest req)
{
    var rawbody = base.Request.GetRawBody();
    var data = req.RequestStream.ReadFully();
    var strdata = UTF8Encoding.UTF8.GetString(data);
    ...
}

And I found that when calling it, rawbody or data is not empty only if content-type is not application/x-www-form-urlencoded. If the content type is application/x-www-form-urlencoded, rawbody and data will be empty.

How do I get the raw request body as a whole (string) when the caller set the content-type to be application/x-www-form-urlencoded?

My current env is ubuntu 16.04 with dotnet core 1.1, don't know if it matters

Upvotes: 2

Views: 1322

Answers (1)

mythz
mythz

Reputation: 143319

ServiceStack uses a forward only request stream that unless you tell ServiceStack to buffer the Request Stream with a pre-request filter:

PreRequestFilters.Add((httpReq, httpRes) => {
    httpReq.UseBufferedStream = true;
});

Either ServiceStack reads or you can read by having your Request DTOs implement IRequiresRequestStream to tell ServiceStack to skip reading the Request Body and that you're going to in your Services.

application/x-www-form-urlencoded requests are special in that if IRequest.FormData is accessed it will trigger reading the Request Body. You can tell ServiceStack to skip reading the FormData when it creates the Request with:

SetConfig(new HostConfig {
    SkipFormDataInCreatingRequest = true
});

Upvotes: 3

Related Questions