从控制台应用程序将参数传递给web api

时间:2016-08-08 17:16:25

标签: c# c#-4.0 asp.net-core asp.net-web-api2

我需要从控制台应用程序与web api进行通信。

api需要传递给它的两个变量/参数:

    [HttpPost("api/loans/range/enroll/{loanStart}/{loanEnd}")]
    public IActionResult PostLoanData(DateTime loanStart, DateTime loanEnd)
    {
        Loans.CreateLoanDates(loanStart, loanEnd);
        return NoContent();
    }

所以在我的主要方法中,我做了类似的事情:

static void Main(string[] args)
{
        var LoanDateRange = new Dictionary<string, string>
                {
                    {"loanStart", startDate.ToString()},
                    {"loanEnd", endDate.ToString()}
                };

        var json = JsonConvert.SerializeObject(LoanDateRange);
        HttpClient client = new HttpClient();
        client.PostAsync("http://mybank1.com/api/loans/range/enroll", new StringContent(json, Encoding.UTF8, "application/json"))
            .ContinueWith(task => {
                var response = task.Result;
                    Console.WriteLine(response.Content.ReadAsStringAsync().Result);
                });
        Console.ReadLine();
 }

当我运行程序时,我只得到一个空例外。

如何从控制台应用程序中为api提供所需内容?或者,我可以更改api,以便更好地与控制台应用程序进行交互吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

试试这种方式

创建模型

class DateModel 
{
    public DateTime LoadStart {get;set;}
    public DateTime LoadEnd {get;set;}
}

然后更新你的api

[HttpPost("api/loans/range/enroll")]
public IActionResult PostLoanData([FromBody] DateModel loan)
{
    Loans.CreateLoanDates(loan.LoadStart, loan.LoadEnd);
    return NoContent();
}

然后从控制台应用程序调用

static void Main(string[] args)
{
    var LoanDateRange = new DateModel();
        LoanDateRange.LoadStart = startDate.ToString();
        LoanDateRange.LoadEnd = endDate.ToString();

    UploadAsync(LoanDateRange);

    Console.ReadLine();
}

public static  async Task UploadAsync(DateModel LoanDateRange)
    {
        using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://mybank1.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                StringContent content = new StringContent(JsonConvert.SerializeObject(LoanDateRange), Encoding.UTF8, "application/json");

                try
                {
                    HttpResponseMessage response = await client.PostAsync("api/loans/range/enroll", content);
                    if (response.IsSuccessStatusCode)
                    {
                        // "Success", MessageBoxButtons.OK);
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }
    }

答案 1 :(得分:1)

以及 Newtonsoft.Json 的最终版本

public class TestClass
{
    [JsonProperty]
    public string Server { get; set; }
    [JsonProperty]
    public string UserName { get; set; }
    [JsonProperty]
    public List<ShareData> Shares { get; set; }
}

 using (var client = new HttpClient()
 {
      string uri = new Uri("http://myapiendpoint/").ToString();

      string content = JsonConvert.SerializeObject(TestClass);
      var response = await client.PostAsync(uri, new StringContent(content, Encoding.UTF8, "application/json"));
 }