如何使处理程序请求返回json

时间:2012-05-17 18:35:31

标签: c# json handler

我有一个返回json

的处理程序
public void ProcessRequest (HttpContext context) {
    HttpResponse response = context.Response;
    response.ContentType = "application/json";

    string controlType = context.Request.QueryString["controlType"];
    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    CmsManager cmsManager = new CmsManager();
    IDictionary<string, Guid> sitefinityPageDictionary = SitefinityUtilities.sitefinityPageDictionary;

    if (string.IsNullOrEmpty(controlType)) {
        response.Write("0");
    }
    else {
        var pagesWithControl = from page in sitefinityPageDictionary
                               from control in cmsManager.GetPage(page.Value).Controls
                               where control.TypeName == controlType
                               select page;
        response.Write(jsonSerializer.Serialize(pagesWithControl));
    }
}

在一个单独的项目中,我想向处理程序发出一个请求,要求使用返回的json对象。

  1. HttpRequest是否是用于向处理程序发出请求的适当对象?
  2. 有人可以提供一个简单的例子,说明如何从另一个c#类(而不是javascript)请求和使用json对象吗?

1 个答案:

答案 0 :(得分:1)

这里有一种方法可以使用c#

中的json对象
IList<MyClass> myClassList = null;
var request = WebRequest.Create(url);
request.ContentType = "application/json; charset=utf-8";

string json;
using (var response = request.GetResponse())
{
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        json = sr.ReadToEnd();
        var javaScriptSerializer = new JavaScriptSerializer();
        myClassList = javaScriptSerializer.Deserialize<List<MyClass>>(json);
    }
}