asp.net mvc5取得post和get的数据和模拟发送

可以放在控制器的入口函数中,这样载入就会被调用

 

asp.net mvc,get+post:

public ActionResult Index()

        {

            if (Request.QueryString.Count > 0)

            {

                foreach (var item in Request.QueryString)

                {

                    Console.WriteLine(item);

                }

            }



            if (Request.Form.Count > 0)

            {

                foreach (var item in Request.Form)

                {

                    Console.WriteLine(item);

                }

            }



            return null;

        }
View Code

 

 

模拟发送post:

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Text;

using System.Threading.Tasks;



namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            var targetWeb = "http://localhost:60797/";

            var reqContent = "Test1=123&Test2=345";



            byte[] data = Encoding.UTF8.GetBytes(reqContent);



            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(targetWeb);

            req.ContentType = "application/x-www-form-urlencoded";

            req.ContentLength = data.Length; 

            req.Method = "POST";

            req.ContentLength = data.Length;

            Stream stream = req.GetRequestStream();

            stream.Write(data, 0, data.Length);

            stream.Close();

            WebResponse resp = req.GetResponse();

            stream = resp.GetResponseStream();



            StreamReader reader = new StreamReader(stream);

            string response = reader.ReadToEnd();

            req.Abort();

            resp.Close();



            Console.WriteLine("发出请求: " + reqContent + " 目标地址: " + targetWeb);

            Console.WriteLine("返回响应: " + response);

            Console.Read();

        }

    }

}
View Code

 

 

模拟发送get:

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Text;

using System.Threading.Tasks;



namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            var targetWeb = "http://localhost:60797?Test1=123&Test2=345";



            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(targetWeb);

            req.ContentType = "application/x-www-form-urlencoded";

            req.Method = "GET";

            WebResponse resp = req.GetResponse();

            var stream = resp.GetResponseStream();



            StreamReader reader = new StreamReader(stream);

            string response = reader.ReadToEnd();

            req.Abort();

            resp.Close();



            Console.WriteLine("目标地址: " + targetWeb);

            Console.WriteLine("返回响应: " + response);

            Console.Read();

        }

    }

}
View Code

 

你可能感兴趣的:(asp.net)