Use C# HttpWebRequest to send json data to web service -
i trying send http request of json data web service. directed web service data null...
here web service:
public bool checkuserexist ([frombody] string email) { list<user> all_users = repo.getusers(); var match = all_users.find(i => i.email == email); if (match == null) { return false; } else { return true; } }
and here http request:
var webaddr = "http://localhost:59305/api/user/checkuserexist"; var httpwebrequest = (httpwebrequest)webrequest.create(webaddr); httpwebrequest.contenttype = "application/json; charset=utf-8"; httpwebrequest.method = "post"; using (var streamwriter = new streamwriter(httpwebrequest.getrequeststream())) { string json = "{\"email\":\"email\"}"; streamwriter.write(json); streamwriter.flush(); } var httpresponse = (httpwebresponse)httpwebrequest.getresponse(); using (var streamreader = new streamreader(httpresponse.getresponsestream())) { var result = streamreader.readtoend(); return redirecttoaction("index"); }
as mentioned...iam using debugger @ web service function...the request directed service variable "email" null
the quick fix change posting. if want api endpoint work [frombody] string email
, should change "json":
string json = "\"a@b.c\""; streamwriter.write(json); streamwriter.flush();
however, may want consider few other changes long term on approach:
- let repo return iqueryable instead of list or other ienumerable. written, return every user database. linq, can leverage lazy initialization , let query matching user instead of every user , find match. not scale well.
- use new httpclient , async functionality in action instead of
httpwebrequest
- instead of manually building json, let .net work , create class gets serialized
with above solutions in place (except first since didn't post data context, didn't want make many assumptions), here examples started:
define shared user search class (shared either in same project or shared dll)
public class usersearch { public string email { get; set; } }
let web api map post against search class
public bool checkuserexist([frombody] usersearch usersearch) { iqueryable<user> all_users = repo.getusers(); var ismatch = all_users.any(i => i.email == usersearch.email); return ismatch; }
change httpclient , use async send api request new search class
public async task<actionresult> check() { using (var client = new httpclient()) { var search = new usersearch() { email = "a@b.c" }; var response = await client.postasjsonasync("http://localhost:59305/api/user/checkuserexist", search); if (response.issuccessstatuscode) { bool exists = await response.content.readasasync<bool>(); // handle exists return redirecttoaction("index"); } else { // handle unsuccessful call throw new exception("application error"); } } }
Comments
Post a Comment