C# Rest API return dynamic object

5.7k views Asked by At

I have an webservice

WebServiceHost webServiceHost= new WebServiceHost(typeof(WebMethods), new Uri(url));
webServiceHost.Open();

public class Fish { public string name = "I am a fish"; }
public class Dog { public int legs = 4; }
public class Cat { public DateTime dt = DateTime.Now;}

One of my webMethods should return a dynamic object

WebMethod:

Solution 1

[OperationBehavior]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/isTest?class={cl}")]
object isTest(string cl)
{
    object obj;

    switch (cl)
    {
        case "fish":
            obj= new Fish();
            break;
        case "dog":
            obj= new Dog();
            break;
        default:
            obj= new Cat();
            break;

    }
    return obj;

}

Solution 2

[OperationBehavior]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/isTest?class={cl}")]
dynamic isTest(string cl)
{
    dynamic obj;

    switch (cl)
    {
        case "fish":
            obj= new Fish();
            break;
        case "dog":
            obj= new Dog();
            break;
        default:
            obj= new Cat();
            break;

    }
    return obj;
}

Both are not working. The response is ERR_CONNECTION_RESET

Any idea how to realise it? Thanks for help.

2

There are 2 answers

2
Eminem On

You are not returning a JSON string. Add the following to your uses:

using System.Web.Script.Serialization;

and the following in your body

return new JavaScriptSerializer().Serialize(obj);

change your return type to string instead of object

0
Chandni K On

You can cast the "HttpResponseMessage" response or you can just send the model object in create response method.

[WebGet(UriTemplate = "{id}")]
public HttpResponseMessage isTest(int id)
{
   Model model = Model.table.Where(p => p.Id == id).FirstOrDefault();
   if (model != null)
   {
      //return Request.CreateResponse<Model>(HttpStatusCode.OK, model);
      //or
      return Request.CreateResponse(HttpStatusCode.OK, model);
   }
   else
   {
      return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Model Not Found");
   }
}