在 ASP.NET 中接收 POST 数据

发布于 2024-08-30 09:55:09 字数 3118 浏览 3 评论 0原文

我想在 C# 桌面应用程序中使用 ASP 生成代码。

为了实现这一目标,我设置了一个简单的主机(派生自 System.MarshalByRefObject),它通过 HttpRuntime.ProcessRequest 处理 System.Web.Hosting.SimpleWorkerRequest。这会处理传入请求指定的 ASPX 脚本(使用 System.Net.HttpListener 等待请求)。

客户端部分由 System.ComponentModel.BackgroundWorker 表示,它构建 System.Net.HttpWebRequest 并接收来自服务器的响应。

我的客户端部分代码的简化版本如下所示:

private void SendRequest(object sender, DoWorkEventArgs e)
{
    // create request with GET parameter
    var uri = "http://localhost:9876/test.aspx?getTest=321";
    var request = (HttpWebRequest)WebRequest.Create(uri);

    // append POST parameter
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    var postData = Encoding.Default.GetBytes("postTest=654");
    var postDataStream = request.GetRequestStream();
    postDataStream.Write(postData, 0, postData.Length);

    // send request, wait for response and store/print content
    using (var response = (HttpWebResponse)request.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            _processsedContent = reader.ReadToEnd();
            Debug.Print(_processsedContent);
        }
    }
}

我的服务器部分代码如下所示(没有异常处理等):

public void ProcessRequests()
{
    // HttpListener at http://localhost:9876/
    var listener = SetupListener();

    // SimpleHost created by ApplicationHost.CreateApplicationHost
    var host = SetupHost();

    while (_running)
    {
        var context = listener.GetContext();

        using (var writer = new StreamWriter(context.Response.OutputStream))
        {
            // process ASP script and send response back to client
            host.ProcessRequest(GetPage(context), GetQuery(context), writer);
        }

        context.Response.Close();
    }
}

到目前为止,只要我只使用 GET,所有这些都可以正常工作 参数。但是当我在 ASPX 脚本中接收 POST 数据时,我遇到了麻烦。为了进行测试,我使用以下脚本:

// GET parameters are working:
var getTest = Request.QueryString["getTest"];
Response.Write("getTest: " + getTest);           // prints "getTest: 321"

// don't know how to access POST parameters:
var postTest1 = Request.Form["postTest"];        // Request.Form is empty?!
Response.Write("postTest1: " + postTest1);       // so this prints "postTest1: "

var postTest2 = Request.Params["postTest"];      // Request.Params is empty?!
Response.Write("postTest2: " + postTest2);       // so this prints "postTest2: "

看来我在 ASP 中处理的 System.Web.HttpRequest 对象不包含有关我的 POST 参数“postTest”的任何信息。我在调试模式下检查了它,没有一个成员既不包含参数名称“postTest”也不包含参数值“654”。我也尝试了Request的BinaryRead方法,但不幸的是它是空的。这对应于Request.InputStream==null 和Request.ContentLength==0。并且让事情变得非常混乱,Request.HttpMethod 成员设置为“GET”?!

为了隔离问题,我使用 PHP 脚本而不是 ASPX 脚本测试了代码。这非常简单:

print_r($_GET);  // prints all GET variables
print_r($_POST); // prints all POST variables

结果是:

Array
(
    [getTest] => 321
)
Array
(
    [postTest] => 654
)

因此,通过 PHP 脚本,我可以访问 POST 数据。为什么 ASPX 脚本不这样做? 我做错了什么? Response 对象中有特殊的访问器或方法吗?

任何人都可以给出提示,甚至知道如何解决这个问题吗?提前致谢。

I want to use ASP for code generation in a C# desktop application.

To achieve this, I set up a simple host (derived from System.MarshalByRefObject) that processes a System.Web.Hosting.SimpleWorkerRequest via HttpRuntime.ProcessRequest. This processes the ASPX script specified by the incoming request (using System.Net.HttpListener to wait for requests).

The client-part is represented by a System.ComponentModel.BackgroundWorker that builds the System.Net.HttpWebRequest and receives the response from the server.

A simplified version of my client-part-code looks like this:

private void SendRequest(object sender, DoWorkEventArgs e)
{
    // create request with GET parameter
    var uri = "http://localhost:9876/test.aspx?getTest=321";
    var request = (HttpWebRequest)WebRequest.Create(uri);

    // append POST parameter
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    var postData = Encoding.Default.GetBytes("postTest=654");
    var postDataStream = request.GetRequestStream();
    postDataStream.Write(postData, 0, postData.Length);

    // send request, wait for response and store/print content
    using (var response = (HttpWebResponse)request.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            _processsedContent = reader.ReadToEnd();
            Debug.Print(_processsedContent);
        }
    }
}

My server-part-code looks like this (without exception-handling etc.):

public void ProcessRequests()
{
    // HttpListener at http://localhost:9876/
    var listener = SetupListener();

    // SimpleHost created by ApplicationHost.CreateApplicationHost
    var host = SetupHost();

    while (_running)
    {
        var context = listener.GetContext();

        using (var writer = new StreamWriter(context.Response.OutputStream))
        {
            // process ASP script and send response back to client
            host.ProcessRequest(GetPage(context), GetQuery(context), writer);
        }

        context.Response.Close();
    }
}

So far all this works fine as long as I just use GET parameters. But when it comes to receiving POST data in my ASPX script I run into trouble. For testing I use the following script:

// GET parameters are working:
var getTest = Request.QueryString["getTest"];
Response.Write("getTest: " + getTest);           // prints "getTest: 321"

// don't know how to access POST parameters:
var postTest1 = Request.Form["postTest"];        // Request.Form is empty?!
Response.Write("postTest1: " + postTest1);       // so this prints "postTest1: "

var postTest2 = Request.Params["postTest"];      // Request.Params is empty?!
Response.Write("postTest2: " + postTest2);       // so this prints "postTest2: "

It seems that the System.Web.HttpRequest object I'm dealing with in ASP does not contain any information about my POST parameter "postTest". I inspected it in debug mode and none of the members did contain neither the parameter-name "postTest" nor the parameter-value "654". I also tried the BinaryRead method of Request, but unfortunately it is empty. This corresponds to Request.InputStream==null and Request.ContentLength==0. And to make things really confusing the Request.HttpMethod member is set to "GET"?!

To isolate the problem I tested the code by using a PHP script instead of the ASPX script. This is very simple:

print_r($_GET);  // prints all GET variables
print_r($_POST); // prints all POST variables

And the result is:

Array
(
    [getTest] => 321
)
Array
(
    [postTest] => 654
)

So with the PHP script it works, I can access the POST data. Why does the ASPX script don't? What am I doing wrong? Is there a special accessor or method in the Response object?

Can anyone give a hint or even know how to solve this? Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你曾走过我的故事 2024-09-06 09:55:09

这可能是编码问题,导致您的请求流被丢弃。您应该使用:

UTF8Encoding.UTF8.GetBytes("postTest=654");

因为您可能会使用“Windows-1252”代码页发送请求。

This might be an encoding issue which results in your request stream being discarded. You should use:

UTF8Encoding.UTF8.GetBytes("postTest=654");

as you will probably be sending the request using "Windows-1252" codepage.

北渚 2024-09-06 09:55:09

从 Web.config 中删除 cookieless="true"

Remove cookieless="true" from Web.config.

半山落雨半山空 2024-09-06 09:55:09

今天我遇到了类似的问题。在我的配置中,这是由 URL 重写规则引起的。该规则将所有页面从 HTTP 重定向到 HTTPS,重定向时 POST 数据丢失。
因此,对我来说,将数据发布到 HTTPS 而不是 HTTP 有所帮助(因为当时该规则不适用)。

Today I had a similar problem. On my configuration, it was caused by a URL-REWRITING rule. The rule was redirecting all pages from HTTP to HTTPS and when redirecting, the POST data were lost.
So for me, posting data to HTTPS instead of HTTP had helped (since the rule did not apply then).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文