Utility to access json

My Servicestack service is sent by Json (via jquery).

sendData = function(dataToSend) { var request; return request = $.ajax({ url: "/api/test", type: "post", data: JSON.stringify(dataToSend), dataType: "json", accept: "application/json", contentType: "application/json" }); 

Json data is properly deserialized if it matches the root properties of my DTO (for example: userId: 'foo' β†’ UserId = foo in the DTO).

I want to access the json source data before it is deserialized to add custom deserialization. So far I have not had problems accessing querystrings with custom filters (RequestFilterAttribute) or if the data was published as a form. Now I see that the data that is published using the Chrome developer tools is in the headers with "Request Payload", so it is neither in FormData nor QueryString, which I can access when debugging my IHttpRequest. How can I get my raw json data in a filter?

0
source share
1 answer

If you want to replace the default deserialization behavior with custom behavior for a specific DTO request, you can do this in your AppHost installation code:

 JsConfig<MyRequestDtoClass>.DeSerializeFn = DeserializeMyRequestDto; 

Where DeserializeMyRequestDto is a function or lambda that takes one string parameter - the body of the raw request - and returns a deserialized instance of your DTO:

 MyRequestDtoClass DeserializeMyRequestDto(string rawBody) { ... } 

RequestFilterAttribute routines purpotedly access the raw request body using request.GetRawBody() , where request is the IHttpRequest object passed to the Execute filter method. But in my experience, GetRawBody returns an empty string because the request input stream seems to be consumed by then due to deserialization. I worked on this once, creating an HTTP module (registered in AppHost via DynamicModuleUtility.RegisterModule ), which will β€œlook” into the request input stream in the BeginRequest event BeginRequest . (The peek function will read the input stream of the request, and then reset the Position stream to where it was originally.)

+2
source

Source: https://habr.com/ru/post/1501491/


All Articles