tags:

views:

60

answers:

3

I am working on an ASP.NET MVC web application in which I have an object with a Uri property. The Uri contains a restful link to a resource in the following form:

/Repository/Dataset/5

The Dataset action of the Repository controller returns the contents of dataset 5 as Json.

How do I call this method from the Uri and interpret the response as Json from within the object?

Many thanks.

A: 

In server side action return JsonResult.

public ActionResult Dataset(int id)
{
  // reository code
  return Json(model);
}

client side call $.getJSON.

takepara
Thanks but I don't want to call the controller method client side, but from a method on an object. I have the controller method defined so what I require is a way to call the controller method from the Uri from anywhere in code - not just from a view/using jQuery.
TonE
A: 

My opinion is that you should not call your controller from anywhere in code.In ASP.NET MVC Controller is there to accept request, take data and choose proper view to be returned back.

Maybe you should add method on repository that is returning already JSONized data, or introduce "Middle man" that can serialize data returned from repository so controller can call middle man to do the job. Then repository (or "Middle man") can be called from anywhere in code.

e.g.(used Json.NET for json serialization):

public class MiddleMan
{
    IRepository repository
    public MiddleMan(IRepository repository)
    {
      this.repository = repository;
    }

    public string GetJsonObjects(int id)
    {
      return JsonConvert.SerializeObject(repository.GetObject(id));
    }

}

then controller (or anywhere in the code) can call this middle class:

public string Dataset(int id)
{
  return new MiddleMan(repository).GetJsonObjects(id);
}
Misha N.
We actually have a service layer providing this middleman functionality. The problem lies with the object containing the Uri property - the data could be located in any source hence the need to describe it with a Uri. Eventually there will probably be a webservice created to serve the content from the Uri rather than rely on a Uri pointing to a controller method.
TonE
A: 

For the time being I'm going to implement a uri extension method something along these lines, creating a WebRequest object for the Uri.

public static string GetContent(this Uri uri)
{
      var myRequest = (HttpWebRequest) WebRequest.Create(uri);
      myRequest.Method = "GET";
      WebResponse myResponse = myRequest.GetResponse();
      var sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
      string result = sr.ReadToEnd();
      sr.Close();
      myResponse.Close();
      return result;
}
TonE