4

I get the feeling I really should be learning WCF for this (feel free to comment if you agree), but, I want to query a website and get a result back, in either XML or JSON format.

In this case, I'm choosing JSON.

I have a controller in a web site (www.site1.com) , which looks like

public JsonResult Save(bool willSave)
{
   //logic with the parameters to go here
   return Json(new { code = 200, description = "OK" }, JsonRequestBehavior.AllowGet);
}

Now, I'd like to get this information from another website, so in www.site2.com I have nothing... I have no idea what code I can write, simply because all of the examples I've seen where you query json uses javascript/Ajax.

I don't want to use JavaScript or Ajax (I know how to do that), for this project I'm trying to do everything I can server side.

I'd like to be able to do the following

public ActionResult Do() 
{
    var json = someHowQuerySite1.com?withQueryString=true;//THIS IS THE ISSUE
    var model = CreateModel(json);
    return View(model);
}

As you can hopefully see,

var json = someHowQuerySite1.com?withQueryString=true;//THIS IS THE ISSUE

I don't know what syntax to write here.

Peter Campbell
  • 661
  • 1
  • 7
  • 35
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120

3 Answers3

5

The simplest way, replace

var json = someHowQuerySite1.com?withQueryString=true;

with

using (var client = new HttpClient())
{
    var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx?withQueryString=true");

    var json = myJsonUtililty.toJson(responseString);
}

HTTP request with post

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
4

You want to use a HttpWebRequest to request www.site1.com/Save?save=true. Something like

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://[urlhere]");
HttpWebResponse response = request.GetResponse();
using(Stream responsestream = response.GetResponseStream())
{
 //Get your JSON from the stream here
}
Nils O
  • 1,321
  • 9
  • 19
1

Use something like this

var response = client.PostAsJsonAsync("UserApi/ValidateUserLogin", new UsersBLL { Username = userName, UserPassword = password }).Result;
Kaushik Thanki
  • 3,334
  • 3
  • 23
  • 50