Is there a .NET ready made method to process response body of a HttpListener HttpListenerRequest body?

前端 未结 3 640
心在旅途
心在旅途 2021-02-07 07:05

I\'m using HttpListener to provide a web server to an application written in another technology on localhost. The application is using a simple form submission (application/x-w

相关标签:
3条回答
  • 2021-02-07 07:14

    If you want to avoid the dependency on System.Web that is required to use HttpUtility.ParseQueryString, you could use the Uri extension method ParseQueryString found in System.Net.Http.

    Make sure to add a reference (if you haven't already) to System.Net.Http in your project.

    Note that you have to convert the response body to a valid Uri so that ParseQueryString (in System.Net.Http)works.

    string body = "value1=randomvalue1&value2=randomValue2";
    
    // "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
    string urlBody = "http://localhost/query?" + body;
    NameValueCollection coll = new Uri(urlBody).ParseQueryString();
    
    0 讨论(0)
  • 2021-02-07 07:28

    The magic bits that fill out HttpRequest.Form are in System.Web.HttpRequest, but they're not public (Reflector the method "FillInFormCollection" on that class to see). You have to integrate your pipeline with HttpRuntime (basically write a simple ASP.NET host) to take full advantage.

    0 讨论(0)
  • 2021-02-07 07:33

    You mean something like HttpUtility.ParseQueryString that gives you a NameValueCollection? Here's some sample code. You need more error checking and maybe use the request content type to figure out the encoding:

    string input = null;
    using (StreamReader reader = new StreamReader (listenerRequest.InputStream)) {
        input = reader.ReadToEnd ();
    }
    NameValueCollection coll = HttpUtility.ParseQueryString (input);
    

    If you're using HTTP GET instead of POST:

    string input = listenerRequest.Url.QueryString;
    NameValueCollection coll = HttpUtility.ParseQueryString (input);
    
    0 讨论(0)
提交回复
热议问题