欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp.net mvc 后台实现post

程序员文章站 2022-03-04 13:01:51
...

有时候前台html里使用ajax post 的时候,可能会遇到跨域问题, 这下可能需要用到后台C# 代码进行post , 

C#中提供了  HttpWebRequest 和 HttpWebResponse  这一对好用的类 , 我写了一段简单的代码, 本人菜鸟, 写错请原谅 。 

 


        private string PostMoths(string url, string param)
        {
            StringBuilder longSTR = new StringBuilder();

            try
            {
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8;";
                //注意:这里可以跟你你在浏览器调试工具中*调整 Request Method   和 Request Headers Content-Type
                //有可能字符集不是UTF8

                string paraUrlCoded = param;
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;

                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();

                System.Net.HttpWebResponse response;
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.Stream rs;
                rs = response.GetResponseStream();

                string StrDate = "";
                StreamReader Reader = new StreamReader(rs, Encoding.UTF8);
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    longSTR.AppendLine(StrDate);
                }
                Reader.Close();
                rs.Close();
            }
            catch(Exception ex)
            {
                longSTR.Append(ex.Message);
            }
            
            return longSTR.ToString();
        }

 

 

在controller 里面使用

public ActionResult GetWebB()
        {
            string result = "";

           
                string url = "http://otherWEB/home/GetQita";
                string param = "id=hello&age=9";
                result = PostMoths(url, param);
           

            return Content(result);
        }