-1

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

来自控制台应用程序的方法调用:

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();


    }
}

}

控制器方法:

[AllowAnonymous]
    [HttpPost]
    public JsonResult AddData(int fileDetailsId)
    {
        var response = new ResponseDTO();
        FileDetails fileDetails = _addingDataDl.GetFileDetails(fileDetailsId);
        bool hasKnowParts = false;
        FileProcess fileProcess = _addingDataDl.GetFileProcess(fileDetailsId, Enumerations.ProcessType.Parsed);
        try
        {
            Entities.User user = _userRepository.GetUserByUserName(User.Identity.Name);
            if (fileDetails != null)
4

2 回答 2

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();
于 2018-06-28T11:26:52.843 回答
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”。

于 2018-06-28T11:28:20.440 回答