如何获取已阅读的内容 [英] How to get hold of Content that is already read

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

问题描述

我有一个继承自 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+body的组合.我可以通过调用 Request.Method 获得的方法和我可以通过调用 Request.RequestUri.ToString() 获得的 url,但我无法像 之前 那样获得正文 它被 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().Result 什么都不返回.这是因为内容只能读取一次.

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天全站免登陆