Generate http post request from controller

后端 未结 3 1298
抹茶落季
抹茶落季 2021-01-05 05:57

Forgive me if this is a stupid question. I am not very experienced with Web programming. I am implementing the payment component of my .net mvc application. The component in

3条回答
  •  感动是毒
    2021-01-05 06:36

    There certainly is a built in library to generate http requests. Below are two helpful functions that I quickly converted from VB.NET to C#. The first method performs a post the second performs a get. I hope you find them useful.

    You'll want to make sure to import the System.Net namespace.

    public static HttpWebResponse SendPostRequest(string data, string url) 
    {
    
        //Data parameter Example
        //string data = "name=" + value
    
        HttpWebRequest httpRequest = HttpWebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        httpRequest.ContentLength = data.Length;
    
        var streamWriter = new StreamWriter(httpRequest.GetRequestStream());
        streamWriter.Write(data);
        streamWriter.Close();
    
        return httpRequest.GetResponse();
    }
    
    public static HttpWebResponse SendGetRequest(string url) 
    {
    
        HttpWebRequest httpRequest = HttpWebRequest.Create(url);
        httpRequest.Method = "GET";
    
        return httpRequest.GetResponse();
    }
    

提交回复
热议问题