MVC 方法接收空值

MVC Method receiving null value

我正在尝试将 2 个参数从控制台应用程序传递到 ASP.NET 控制器中的方法。
当我尝试这样做时,参数不断收到空值。

这是客户端的代码

HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://localhost:44331/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            Dictionary<string, string> data = new Dictionary<string, string>
            {
              
                { "user12",u},
                { "pass12",p},

            };
            List<Dictionary<string, string>> x = new List<Dictionary<string, string>>();
            x.Add(data);
            HttpResponseMessage response = client.PostAsJsonAsync("Home/Receiver", x).Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("success!!");            
            }

其中 up 是用户在控制台应用 运行s 时定义的参数。

这是我要将参数传递给方法的代码

[HttpPost]  
public void Receiver(string user12, string pass12) 
{
    MessageBox.Show("user is " + user12 +"and pass is"  + pass12);
}

基本上,我想将参数up从客户端传递到方法中的参数user12pass12。但是,当我运行代码时,值为user12,pass12为null!!

当我尝试通过 postman 发出 post 请求时,它成功了。

非常感谢任何帮助。

试试这个:

public static async Task GetData(string u, string p)
{
           using (var client = new HttpClient())
          {
            var contentType = new MediaTypeWithQualityHeaderValue("application/json");
            var baseAddress = "https://localhost:44331";
            var api = "/Home/Receiver";
            client.BaseAddress = new Uri(baseAddress);
            client.DefaultRequestHeaders.Accept.Add(contentType);
           var data = new Dictionary<string, string>
            {
              
                { "user12",u},
                { "pass12",p},

            };
     var jsonData = JsonConvert.SerializeObject(data);
        var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");
            var response = await client.PostAsync(baseAddress + api,contentData);
                        
            if (response.IsSuccessStatusCode)
            {
                var stringData = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<object>(stringData);
            }
       }
}

这是你的程序

public class Program
{
    static async Task Main(string[] args)
   {
        var u="user";
         var p="password";
        await GetData(u,p);
        Console.WriteLine("finished");
        
    }

    public static async Task GetData(string u, string p)
    {
          ...code above
    }

 
}

并修正你的行为

添加模型class

public class Model
    {
        public string User12 { get; set; }
        public string Pass12 { get; set; }
    }

并更正操作 header

        public void Receiver(Model model) 
        {
             MessageBox.Show("user is " + model.User12 +"and pass is"  + model.Pass12);
        }