如何从控制台应用程序调用控制器中的方法

时间:2018-06-28 11:19:58

标签: c# asp.net-mvc controller console-application

我试图从控制台应用程序中调用控制器(mvc)中的方法,它以整数值作为参数。如何将控制台应用程序中的整数值作为参数传递给控制器​​。如何运行它并检查。

从控制台应用程序调用方法:

let url = new URL('https://test.website.com?c=1&b=2');

let b = url.searchParams.get('b');
let c = url.searchParams.get('c');

console.log(`B: ${b}\nC: ${c}`);

}

控制器方法:

public class Program
{
    public static void Main()
    {


        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:60035/AddDataToDataBaseController/AddData");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        var response = (HttpWebResponse)httpWebRequest.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();


    }
}

2 个答案:

答案 0 :(得分:0)

这有两个问题:

一个是URL中控制器的名称。应该改为AddDataToDataBase

第二个缺少整数参数。在请求中添加参数。尝试以下代码。

byte[] data = Encoding.ASCII.GetBytes("fileDetailsId=1");//Prepare data to write to write to request
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:60035/AddDataToDataBase/AddData");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = data.Length;//Here you set the content length
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(data, 0, data.Length);//Here you write your parameters to the request
var response = (HttpWebResponse)httpWebRequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

答案 1 :(得分:0)

您必须将参数放入POST数据中。这是通过写入WebRequest的RequestStream来完成的。像这样:

var filedetails = "filedetails=1";
var data = Encoding.ASCII.GetBytes(filedetails);
var requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();

您还必须将内容类型更改为“ application / x-www-form-urlencoded”。