C#Rest API返回动态对象

时间:2016-03-22 06:45:45

标签: c# json webmethod webservicehost

我有一个网络服务

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

我的一个webMethods应该返回一个动态对象

的WebMethod:

解决方案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;

}

解决方案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;
}

两者都不起作用。响应是ERR_CONNECTION_RESET

任何想法如何实现它? 感谢帮助。

2 个答案:

答案 0 :(得分:0)

您没有返回JSON字符串。 添加以下内容:

using System.Web.Script.Serialization;

以及您身体中的以下内容

return new JavaScriptSerializer().Serialize(obj);

将您的退货类型更改为string而不是object

答案 1 :(得分:0)

您可以转换“HttpResponseMessage”响应,也可以只在create response方法中发送模型对象。

var yourQuery = Context.STopics.AsQueryable(); 
var yourParam = "ALL";
if(yourParam != "ALL")
   yourQuery = yourQuery.Where(x => x.IsActive==true && x.StudentID == 123);

var abc = yourQuery.Select(x=> new result()
                               {
                                  name = st.name 
                               }).ToList();