Retrieve HTTP POST request containing XML - c#

I need to setup a web page that listens for XML document via an HTTP POST. I don't need to POST out, I need to receive that POST. What object does this? Should I use an HTTP handler, web service, webRequest, Stream or something else? I need to use a IIS Server and prefer C#.
I've Tried...
I dont think I can use WebRequest since I'm not sending a request, just waiting for them.
"HttpRequest.InputStream" but I'm not sure how to use it or where to put it. Do i need to use it with a web service or a asp.net application? I put it in
http://forums.asp.net/t/1371873.aspx/1
I've tried a simple web service http://msdn.microsoft.com/en-us/library/bb412178.aspx - But when i try to visit "http://localhost:8000/EchoWithGet?s=Hello, world!", i get a "webpage cannot be found error"
If anyone has any helpful code or links that would be great!
EDIT:
I am trying to receive notifications from another program.

You could write an ASP.NET application that you will host in IIS in which you could either have an .ASPX page or a generic .ASHX handler (depending on how you want the result to be formatted - do you want to return HTML or some other type) and then read the Request.InputStream which will contain the body of the request that comes from the client.
Here's an example of how you could write a generic handler (MyHandler.ashx):
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var stream = context.Request.InputStream;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
string xml = Encoding.UTF8.GetString(buffer);
... do something with the XML
// We only set the HTTP status code to 202 indicating to the
// client that the request has been accepted for processing
// but we leave an empty response body
context.Response.StatusCode = 202;
}
public bool IsReusable
{
get
{
return false;
}
}
}

I'm not sure where to call or use the handler. This is what i have so far...
Default.aspx
<%#Page Inherits="WebApplication1._Default"%>
<%#OutputCache Duration="10" Location="Server" varybyparam="none"%>
<script language="C#" runat="server">
void Page_Init(object sender, EventArgs args) {
}
}
</script>
<html>
<body>
</body>
</html>
Default.aspx.cs
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpContext contex = Context;
MyHandler temp = new MyHandler();
temp.ProcessRequest(context);
}
}
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var stream = context.Request.InputStream;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
string xml = Encoding.UTF8.GetString(buffer);
... do something with the XML
// We only set the HTTP status code to 202 indicating to the
// client that the request has been accepted for processing
// but we leave an empty response body
context.Response.StatusCode = 202;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

Related

How to know Html Request Recieved in win form?

Im working on a win form project that I should get some information from specific URL.
I mean I should listen to this url :
http://xxx.xxx.xxx.xxx:8080/getsms
and when It will change to
http://xxx.xxx.xxx.xxx:8080/getsms?Destination=$Destination&Source=$Source&ReceiveTime=$ReceiveTime&MsgBody=$MsgBody
and I have to parse the contex as well.
so how can I know when exactly there is a request in this url?
Is it a good way that I use httpListener? Its my code for that:
public static void SimpleListenerExample(string[] prefixes)
{
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
//Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}
private void button2_Click(object sender, EventArgs e)
{
string[] test = { "http://www.damavand.co.ir:80/" };
SimpleListenerExample(test);
}
but it has not worked. I dont know why. It dosent have any error, but I cant get any response. should I set any server configuration? How? and how can I test my program that I be sure there is a request.
Thanks for any response ...

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);
A nice way of doing it is to use Routing.
In the 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");
}
This is telling ASP.Net to call your handler on /Something/GetData/XXX/YYY/data.json.
You can can access Route Parameters in the handler:
context.Request.RequestContext.RouteData.Values["par1"].
The crawler will parse URLs as long as they are referenced somewhere (i.e. robots file or links)
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);
}
Your Problem is
Load Content into Div using Javascript in ASP.NET using C#.
Visible to Search Engines
My Opinion
When You want Update Partial Page there are some handler or service to communicate between server and client You can Using Ajax for Request to server.
if you use jquery you can try this function jQuery.ajax(); example:
$.ajax({
url:"/webserver.aspx",
data:{id:1},
type:'POST',
success: function(data) {
//do it success function
}
}) ;
Next Step is Generate Web Service in Code behind Your ASP.NET that should be result as JSON or XML format, whatever you use make sure you can parse easily in success function of jQuery.ajax();
Here some Reference for Generate Web Service on ASP.NET
Generate JSON Web Service ASP.NET
Parse Json on Code Behind Parse JSON Code Behind
Generate JSON RESULT and Parse using Client Side Javascript Web Services ASP.NET Json
2.Visible to Search Engine actually
I think if You allow Search engine to Index your page it's no problem , Even if You have some Ajax Code , Search engine will be indexing your page.
I've found this article, I believe this will help you.
http://www.overpie.com/aspnet/articles/csharp-post-json-to-generic-handler

Event when response has been sent

I have a controller class which inherits from ApiController and handles HTTP requests from a client.
One of the actions generates a file on the server and then sends it to the client.
I'm trying to figure out how to clean up the local file once the response has been fulfilled.
Ideally this would be done through an event which fires once a response has been sent to the client.
Is there such an event? Or is there a standard pattern for what I'm trying to achieve?
[HttpGet]
public HttpResponseMessage GetArchive(Guid id, string outputTypes)
{
//
// Generate the local file
//
var zipPath = GenerateArchive( id, outputTypes );
//
// Send the file to the client using the response
//
var response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(zipPath, FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
response.Content.Headers.ContentLength = new FileInfo(zipPath).Length;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(zipPath)
};
return response;
}
Take a look at the OnResultExecuted event - you can add a custom filter to the method and handle the event there.
public class CustomActionFilterAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
///filterContext should contain the id you will need to clear up the file.
}
}
The EndRequest event in Global.asax may also be an option.
public override void Init() {
base.Init();
EndRequest += MyEventHandler;
}

Execute a aspx page from windows application and get data returned

Hi am working on a windows application in which i have to call a aspx page which read values from database and convert it into an XML.I have no clue how to call a aspx page and make it return a value to the calling windows application.I tried using Web request method it doesnot return anything.Please suggest me a idea how to do this
You can use WebClient, something like this :
this is a sitemap XML generated by HttpModule that intercepts requests for XML files:
WebClient wc = new WebClient();
string smap = wc.DownloadString("http://www.antoniob.com/sitemap.xml");
And this is a theoretical aspx that returns XML
WebClient wc = new WebClient();
string smap = wc.DownloadString("http://www.somesite.com/GetXml.ashx");
There is no difference in the call, except of course in address
On Server side (asp.net app), it would be better to use ASHX handler since is more suited for returning XML, In your ASP.NET application add new item, and choose generic handler :
and here is the code for GetXml.ashx handler that will return sample XML from App_Data folder :
public class GetXml : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/xml";
string xml = File.ReadAllText(context.Server.MapPath("~/App_Data/sample.xml"));
context.Response.Write(xml);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}

Expect: 100-Continue - How to Write Module and Test Client

I'm trying to test the behavior of an "expect: 100-continue" request being handled in an IHttpModule.
What I want to do is create a request in a client with the header expect: 100-continue and send it to the server. The server will immediately return a 500. Theoretically, the payload (file) should never be sent if the server returns a 500 instead of a 100.
I'm not seeing the expected behavior. This is what I'm doing...
Here is the server code (http module):
using System;
using System.Web;
namespace WebSite
{
public class Expect100ContinueModule : IHttpModule
{
private HttpApplication httpApplication;
public void Init(HttpApplication context)
{
httpApplication = context;
context.BeginRequest += ContextBeginRequest;
}
private void ContextBeginRequest(object sender, EventArgs e)
{
var request = httpApplication.Context.Request;
var response = httpApplication.Context.Response;
if(!request.Url.AbsolutePath.StartsWith("/Upload"))
{
return;
}
response.StatusCode = 500;
response.End();
}
public void Dispose()
{
}
}
}
I'm running this in IIS 7 with the integrated pipeline.
Here is the client code:
using System.IO;
using System.Net;
namespace ConsoleClient
{
class Program
{
static void Main(string[] args)
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost:83/Upload/");
request.ServicePoint.Expect100Continue = true;
request.Method = "POST";
request.ContentType = "application/octet-stream";
var buffer = File.ReadAllBytes("Test - Copy.txt");
var text = File.ReadAllText("Test - Copy.txt");
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Flush();
}
var response = (HttpWebResponse)request.GetResponse();
var x = "";
}
}
}
From what I'm seeing, the request has the file content even when the 500 is returned.
One issue I ran into is, Fiddler automatically handles expect: 100-continue by buffering the request, returning 100, and continuing with the full request.
I then tried WireShark. To get that to work, I had to capture the traffic with RawCap and read the output with WireShark. From what I can tell, this still shows the full payload on the request.
Now I have a few questions.
Is the server code actually returning the 500 first, or has a 100 already been returned before I get the BegineRequest event?
Is there a better way to write the client? I don't understand why you would write your full payload to the request stream before the request is made. The server module doesn't get the BeginRequest event until the clients Request.GetResponse() method is called.
Is there a good way to test the actual traffic on localhost?
[Update]
I couldn't find a way to test locally so I used a neighbor employees desktop to test with also. I was able to test with WireShark this way.
From what I can tell, there is no way to have the HttpWebClient do a PUT request to IIS without having the full file sent, even if an IHttpModule returns an error immediately before the file is completely uploaded.
I don't know if the issue is in the client (HttpWebClient) or the server (IIS). I don't know if using raw sockets and implementing the HTTP protocol by hand would make a difference.
If anyone has any more insight into this, please let me know.

Categories