Retrieving POST data in C# ASP.NET

2019-06-10 02:44发布

问题:

I'm having troubles to make my program work correctly - here I explain :

  • I have, on one hand a C# WinForms app which launches an instance of IE by using the "Navigate" method : myWebBrowser.Navigate(myUrl, "_blank", intarray, "");, with intarray defined like this : byte[] intarray = BitConverter.GetBytes(id);. On this side, it works.
  • On the other side, I have an ASP .NET WebForms application which has to retrieve this intarray. I've tried this.

    if (HttpContext.Current != null)
    {
        if (Session["Authenticated"] == null)
        {
            var current = HttpContext.Current;
            byte[] postdata = getpostdata(current);
        }
    }
    
    private byte[] getpostdata(HttpContext CurrentContext)
    {
        MemoryStream ms = new MemoryStream();
        CurrentContext.Request.InputStream.CopyTo(ms);
        byte[] postdata = ms.ToArray();
        return postdata;
    }
    // Convert a byte array to an Object
    public int ByteArrayToInt(byte[] arrBytes)
    {
        if (BitConverter.IsLittleEndian) Array.Reverse(arrBytes);
        int i = BitConverter.ToInt32(arrBytes, 0);
        return i;
    }
    

The problem seems to be in retrieving the Data in the getpostdata(HttpContext) function... I get a byte array with length = 0 instead of the one which is sent with length = 4... Does anyone know how to make it work ?

Yann

回答1:

var current = HttpContext.Current;
var sr = new StreamReader(Request.InputStream, Encoding.Default);
var postdata = sr.ReadToEnd();

above