Get["/"] = _ =>"some data";
Post["/"] = _ =>new {detail="detail.."};
我需要将响应转换为此格式
{
state: state code
data: origin data
}
所以,我添加了一个后挂钩
After.AddItemToEndOfPipeline(ResponseFormatHook);
...
private void ResponseFormatHook(NancyContext ctx)
{
var apiResponse = new APIResponse();
apiResponse.State = ctx.Response.StatusCode;
using(var stream = new MemoryStream())
{
ctx.Response.Contents.Invoke(stream);
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
// get the origin data
var content = reader.ReadToEnd();
apiResponse.Data = content;
}
}
var response = new JsonResponse(apiResponse, new DefaultJsonSerializer());
response.StatusCode = HttpStatusCode.OK;
ctx.Response = response;
}
Get["/"]
,没关系。将返回{state:200,data:"some data"}
。
但对于Post["/"]
,将返回{state:200,data:"{detail:\"detail..\"}"}
。数据转换为字符串而非对象。客户端无法立即反序列化。
那么,我怎样才能获得原始数据?
apiResponse.Data=OriginData
,这没关系。
编辑1
也许我可以将数据反序列化为
apiResponse.Data=JsonConvert.Deserialize(apiResponse.Data)
。
但我觉得这个花费太多了,不是吗?
答案 0 :(得分:1)
使用IResponseProcessor
将触摸原始数据。
public class APIResponseProcessor : IResponseProcessor
{
private static readonly IEnumerable<Tuple<string, MediaRange>> extensionMappings =
new[] {new Tuple<string, MediaRange>("json", MediaRange.FromString("application/json"))};
public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
var match = new ProcessorMatch();
match.ModelResult = MatchResult.DontCare;
match.RequestedContentTypeResult = MatchResult.ExactMatch;
return match;
}
public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)
{
var apiResponse = new APIResponse();
apiResponse.Data = model;
return new JsonResponse(apiResponse,new DefaultJsonSerializer());
}
public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings { get { return extensionMappings; } }
}
使用处理器代替After hook。