如何获得内容保持在已经读 [英] How to get hold of Content that is already read

查看:138
本文介绍了如何获得内容保持在已经读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从ApiController继承的类。它有一个PUT方法是这样的:

I have a class that inherits from ApiController. It has a Put-method like this:

[PUT("user/{UserId}")]
public HttpResponseMessage Put(string userId, PaymentRequest paymentRequest)
{
    // Calling business logic and so forth here
    // Return proper HttpResponseMessage here
}

该方法工作正常,因为它是以上。现在我需要验证方法调用的签名,但在这里,我遇到一个问题。签名是基本上法+ URL +体的组合。该方法我可以通过调用Request.Method和URL,我可以通过调用Request.RequestUri.ToString()获取得到的,但我不能让身体保持原样它会自动反序列化到由asp.net MVC4框架PaymentRequest对象。

The method works fine as it is above. Now I need to validate the signature of the method call, but here I run into a problem. The signature is essentially a combination of method + url + body. The method I can get by calling Request.Method and the url I can get by calling Request.RequestUri.ToString(), but I can't get hold of the body as it was before it was automatically deserialized into a PaymentRequest object by the asp.net MVC4 framework.

我的第一次尝试:
正如我现在明白Request.Content.ReadAsStringAsync()。结果返回什么。这是因为内容只能被读取一次。

My first try: As I have now understood Request.Content.ReadAsStringAsync().Result returns nothing. This is because the content can only be read once.

我的第二次​​尝试:
我试图序列化回JSON字符串。

My second try: I tried to serialize it back to a JSON string.

var serializer = new JavaScriptSerializer();
var paymentRequestAsJson = serializer.Serialize(paymentRequest);

这里的问题是,格式化原来比签名的主体部略有不同。它具有相同的数据,但是一些更多的空间。

The problem with this is that the formatting turns out slightly different than the body part of the signature. It has the same data, but some more spaces.

我不能改变什么我PUT方法的调用程序,因为这是一个第三方组件。我应该怎么办?

I can't change what the caller of my Put-method does, as this is a third party component. What should I do?

推荐答案

您可以从底层请求阅读:

You could read from the underlying request:

using (var stream = new MemoryStream())
{
    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
    context.Request.InputStream.Seek(0, SeekOrigin.Begin);
    context.Request.InputStream.CopyTo(stream);
    string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}

这篇关于如何获得内容保持在已经读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆