Servicestack accessing json

萝らか妹 提交于 2019-12-24 13:26:23

问题


My Servicestack service is beeing posted Json (by 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"
  });

The Json data is correctly deserialized if it corresponds to the root properties of my DTO (eg: userId:'foo' -> UserId=foo in the DTO).

I want to access the raw json posted data before it gets deserialized for adding custom deserialization. Till now I had no problems accessing the querystrings with custom filters (RequestFilterAttribute) or if data vas posted like form. Now I see the data that gets posted with Chrome Developer Tools is in the headers with "Request Payload" so it is nor in FormData and nor QueryString I can access when debugging my IHttpRequest. How can I get my raw json data in the filter?


回答1:


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

JsConfig<MyRequestDtoClass>.DeSerializeFn = DeserializeMyRequestDto;

Where DeserializeMyRequestDto is a function or lambda taking a single string param - the raw request body - and returning the deserialized instance of your DTO:

MyRequestDtoClass DeserializeMyRequestDto(string rawBody) { ... }

RequestFilterAttribute subclasses purpotedly have access to the raw request body using request.GetRawBody(), where request is the IHttpRequest object passed into the filter's Execute method. But in my experience, GetRawBody returns an empty string, because the request input stream seems to be consumed by that time due to the deserialization. I worked around this once by creating an HTTP module (registered in AppHost via DynamicModuleUtility.RegisterModule) that would "peek" at the request input stream in a BeginRequest event handler. (The "peek" function would read the request input stream and then reset the Position of the stream to where it initially was.)



来源:https://stackoverflow.com/questions/17919853/servicestack-accessing-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!