Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send data to a generic handler that accepts JSON data using C#

I have a situation where I am accessing an ASP.NET Generic Handler to load data using JQuery. But since data loaded from JavaScript is not visible to the search engine crawlers, I decided to load data from C# and then cache it for JQuery. My handler contains a lot of logic that I don't want to apply again on code behind. Here is my Handler code:

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

I can call the function getUserControlMarkup() from C# but I will have to apply some URL based conditions while calling it. The contentType.typeOfContent is actually based on URL parameters.

If possible to send JSON data to this handler then please tell me how to do that. I am trying to access the handler like this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Common.host + "Handlers/SideContentLoader.ashx?typeOfContent=1&UCArgs=cdata");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

But its giving NullReferenceException in Handler code at line: ContentType contentType = jsonSerializer.Deserialize<ContentType>(jsonString);

like image 716
Aishwarya Shiva Avatar asked Apr 18 '14 15:04

Aishwarya Shiva


1 Answers

Not sure why you want to do it, but to add a content to an HTTP request use:

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);
        }
like image 114
Stefano Altieri Avatar answered Oct 18 '22 09:10

Stefano Altieri