简体   繁体   中英

How to make a httprequest body in asp.net

I've always done my web services in PHP. Now I'm trying some ASP.NET on a project and I found myself on a tricky situation. I have the following C# code, behaving as a "client"

public void sendRequest(string URL, string JSON)
{

    ASCIIEncoding Encode = new ASCIIEncoding();
    byte[] data = Encode.GetBytes(JSON);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
    request.Method = "POST";
    request.ContentLength = data.Length;
    request.ContentType = "application/x-www-form-urlencoded";
    request.CookieContainer = cookieContainer;


    Stream dataStream = request.GetRequestStream();
    dataStream.Write(data, 0, data.Length);
    dataStream.Close();


    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    WebHeaderCollection header = response.Headers;

    var encoding = ASCIIEncoding.ASCII;
    string responseText;
    using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
    {
         responseText = reader.ReadToEnd();
    }

    returnRequestTxtBx.Text = responseText;
}

Well, now I want to handle on the ASPX.CS side... my question is... how do I access the data I sent as a POST? Is there a way in the "Page_Load" method that I can handle the JSON I sent?

To read post method data on your server side read HttpContext.Request.Form method:

protected void Page_Load(object sender, EventArgs e)
{
     string value=Request.Form["keyName"];
}

Or if you want to access row body data simply read: Request.InputStream .

And if you want handle Json format consider Newtonsoft.Json packege .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM