[英]Send data to a generic handler that accepts JSON data using C#
我有一種情況,我正在訪問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;
}
}
我可以從C#調用函數getUserControlMarkup()
但我必須在調用它時應用一些基於URL的條件。 contentType.typeOfContent
實際上基於URL參數。
如果可能將JSON數據發送到此處理程序,請告訴我如何執行此操作。 我試圖像這樣訪問處理程序:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Common.host + "Handlers/SideContentLoader.ashx?typeOfContent=1&UCArgs=cdata");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
但是它在Handler代碼中給出了NullReferenceException
: 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");
}
這告訴ASP.Net在/Something/GetData/XXX/YYY/data.json
上調用你的處理程序。
您可以在處理程序中訪問Route Parameters: context.Request.RequestContext.RouteData.Values["par1"]
。
只要在某處引用URL(即機器人文件或鏈接),抓取工具就會解析URL
你的問題是
我的看法
如果你使用jquery你可以嘗試這個函數jQuery.ajax();
例:
$.ajax({
url:"/webserver.aspx",
data:{id:1},
type:'POST',
success: function(data) {
//do it success function
}
}) ;
下一步是在ASP.NET后面的代碼中生成Web服務,應該以JSON或XML格式生成,無論您使用什么,請確保您可以在jQuery.ajax();
成功函數中輕松解析jQuery.ajax();
這里有一些ASP.NET上生成Web服務的參考
生成JSON Web服務ASP.NET
解析Jason代碼背后的Parse JSON代碼
使用客戶端Javascript Web服務ASP.NET Json生成JSON RESULT和Parse
2.實際上對搜索引擎可見
我想如果您允許搜索引擎為您的頁面編制索引就沒問題,即使您有一些Ajax代碼,搜索引擎也會將您的頁面編入索引。
不確定為什么要這樣做,但要將內容添加到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);
}
我發現這篇文章,我相信這會對你有所幫助。 http://www.overpie.com/aspnet/articles/csharp-post-json-to-generic-handler
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.