c# - Pass parameters to web api from console application -


i need communicate web api console application.

the api needs 2 variables/parameters passed so:

    [httppost("api/loans/range/enroll/{loanstart}/{loanend}")]     public iactionresult postloandata(datetime loanstart, datetime loanend)     {         loans.createloandates(loanstart, loanend);         return nocontent();     } 

so in main method, did this:

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

when run program null exception.

how can give api needs console application? or maybe, can change api can better interact console app?

thanks!

try way

create model

class datemodel  {     public datetime loadstart {get;set;}     public datetime loadend {get;set;} } 

then update api

[httppost("api/loans/range/enroll")] public iactionresult postloandata([frombody] datemodel loan) {     loans.createloandates(loan.loadstart, loan.loadend);     return nocontent(); } 

then call console app

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                 }             }     } 

Comments