Ais*_*iva 8 javascript c# asp.net jquery json
我有一种情况,我正在访问ASP.NET Generic Handler以使用JQuery加载数据.但是,由于从JavaScript加载的数据对搜索引擎抓取工具不可见,我决定从C#加载数据,然后将其缓存为JQuery.我的处理程序包含很多逻辑,我不想再在后面的代码上应用.这是我的Handler代码:
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
string jsonString = string.Empty;
context.Request.InputStream.Position = 0;
using (var inputStream = new System.IO.StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
ContentType contentType = jsonSerializer.Deserialize<ContentType>(jsonString);
context.Response.ContentType = "text/plain";
switch (contentType.typeOfContent)
{
case 1: context.Response.Write(getUserControlMarkup("SideContent", context, contentType.UCArgs));
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以getUserControlMarkup()从C#调用该函数,但我必须在调用它时应用一些基于URL的条件.该contentType.typeOfContent实际上是基于URL的参数.
如果可能将JSON数据发送到此处理程序,请告诉我如何执行此操作.我试图像这样访问处理程序:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Common.host + "Handlers/SideContentLoader.ashx?typeOfContent=1&UCArgs=cdata");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Run Code Online (Sandbox Code Playgroud)
但它NullReferenceException在行中给出了Handler代码:
ContentType contentType = jsonSerializer.Deserialize<ContentType>(jsonString);
一个很好的方法是使用路由.在Global.asax中
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
private void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpHandlerRoute("MyRouteName", "Something/GetData/{par1}/{par2}/data.json", "~/MyHandler.ashx");
}
Run Code Online (Sandbox Code Playgroud)
这告诉ASP.Net打电话给你的处理程序/Something/GetData/XXX/YYY/data.json.
您可以在处理程序中访问Route Parameters :
context.Request.RequestContext.RouteData.Values["par1"].
只要在某处引用URL(即机器人文件或链接),抓取工具就会解析URL
不确定为什么要这样做,但要将内容添加到 HTTP 请求中,请使用:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Common.host + "Handlers/SideContentLoader.ashx?typeOfContent=1&UCArgs=cdata");
var requestStream = request.GetRequestStream();
using (var sw = new StreamWriter(requestStream))
{
sw.Write(json);
}
Run Code Online (Sandbox Code Playgroud)