C# Winform 上传数据到asp.net MVC 控制器

it2025-08-11  7

C# Winform 上传数据到asp.net MVC 控制器

1、先创建一个winform窗口项目

public Form1() { InitializeComponent(); string name = "admin"; string password = "admin"; GetHttp(name,password); } public void GetHttp(string name,string password) { try { WebRequest webRequest = WebRequest.Create($"https://localhost:44307/Home/GetUserInfo?name={name}&password={password}");//这里的地址是你运行web项目的地址,不知道的可以在web控制器中查看 webRequest.Method = "POST"; Stream stream = webRequest.GetRequestStream(); stream.Close(); WebResponse webResponse = webRequest.GetResponse(); System.Text.Encoding resEncoding = System.Text.Encoding.GetEncoding("utf-8");//接收的编码 StreamReader reader = new StreamReader(webResponse.GetResponseStream(), resEncoding); string html = reader.ReadToEnd(); //接收的Html MessageBox.Show("=========" + html); reader.Close(); webResponse.Close(); } catch (Exception ex) { MessageBox.Show("error"); } } 在web控制器中查看http地址:

这里是引用

2、在创建asp.net MVC项目,新建控制器和页面。这里注意新建的控制器名、方法名和地址要对应

public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public void GetUserInfo(string name, string password) { Response.ContentEncoding = Encoding.GetEncoding("UTF-8"); if (username != "" && username == "admin" && password != "" && password == "admin") { Response.Write("success"); } else { Response.Write("error" + Request.Url.Host); } }

3、先运行web项目在运行winform项目,以上URL只适用本机发送、接收,如果需要用另外一台电脑接收,但是执行到WebResponse webResponse = webRequest.GetResponse();报出“400服务器错误”可以先配置IIS Express,再添加保留地址。 修改配置文件

IIS Express的配置文件为 文稿(文档库|我的文档)\IISExpress\config\applicationhost.config,用文本编辑器(记事本即可)打开此文件。搜索要允许外部访问的程序的名称,形同如下代码:

<site name="Cis.Csc.Web" id="10"> <application path="/" applicationPool="Clr4IntegratedAppPool"> <virtualDirectory path="/" physicalPath="C:\Users\Frank\Source\Repos\newhealthylife-csc\Cis.Csc.Web" /> </application> <bindings> <binding protocol="http" bindingInformation="*:43944:localhost" /> </bindings> </site>

在第6行之后添加如下配置

  <binding protocol="http" bindingInformation="*:端口号:计算机名或IP地址" />

添加保留地址 在cmd命令行中执行以下命令:

httpcfg set urlacl /u http://计算机名或IP地址:43944/ /a D:(A;;GX;;;WD)  (Windows XP)

netsh http add urlacl url=http://计算机名或IP地址:43944/ user=everyone  (Windows 7或更高,以管理员身份的运行cmd)

最新回复(0)