Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

c# - How to get hold of Content that is already read

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
}

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.

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...