asp.net mvc 后台实现post

本文介绍如何使用C#的HttpWebRequest和HttpWebResponse类来解决跨域问题,通过一个具体的示例展示了如何发送POST请求并接收响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候前台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);
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值