从控制台应用程序调用MVC动作

本文关键字:MVC 动作 调用 应用程序 控制台 | 更新日期: 2023-09-27 18:17:08

我想从控制台应用程序调用mvc4动作

action url = xyz动作参数(Datetime lastUpdateTime)

这是我的代码

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["StoryBoardSchedulerJobUrl"]);
            webRequest.Method = "POST";
            var data = string.Format("lastUpdateTime={0}", Uri.EscapeDataString(DateTime.Now.ToString()));
            StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
            requestWriter.Write(data);
            requestWriter.Close();
            var response = (HttpWebResponse)webRequest.GetResponse();   

从控制台应用程序调用MVC动作

  1. 编码您的数据(UTF8)
  2. 指定ContentTypeContentLength
  3. 将编码的数据写入请求流

示例

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["StoryBoardSchedulerJobUrl"]);
webRequest.Method = "POST";
var data = string.Format("lastUpdateTime={0}", Uri.EscapeDataString(DateTime.Now.ToString()));
byte[] byteArray = Encoding.UTF8.GetBytes(data);
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.ContentLength = byteArray.Length;
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(byteArray);
requestWriter.Close();
var response = (HttpWebResponse)webRequest.GetResponse();