【问题标题】:Can't get Request.QueryString or similar methods to work无法使用 Request.QueryString 或类似方法
【发布时间】:2015-09-06 19:59:21
【问题描述】:

遗憾的是,因为我几乎不会 C#,所以我无法从 URL 中读取参数。

我在 IIS 7 上将 C# cgi 可执行文件作为应用程序运行。调用可执行文件的url如下:

https://server/cgi/showEmail/showEmail.exe?email=john@gmail.com

代码开头如下:

using System;
using System.Web; // <---- isn't this for Request.QueryString ?
using System.Web.UI;
using System.Collections;
using System.Collections.Specialized;
using System.Data.SqlClient;

class showEmail
{
    static void Main(string[] args)
    {

        Console.WriteLine("\r\n\r\n");
        Console.WriteLine("<h1>Test</h1>");

        try
        {

现在,如果我使用下面的代码,程序会编译,但在浏览器中执行时会出现 null 异常:

        string email = HttpContext.Current.Request.QueryString["email"];

System.NullReferenceException:对象引用未设置为对象的实例。在 showEmail.Main(String[] args)

如果我在下面使用这段代码,乐趣已经在编译器处停止,编译器会给出“当前上下文”异常:

       string email = Request.QueryString["email"];

错误 CS0103:当前上下文中不存在名称“请求”

...

我是否遗漏了可执行文件查看 url 参数所需的基本内容?

编辑:我已经浏览了 sof 和许多其他地方,但到目前为止还无法在这个问题上连接点。

【问题讨论】:

  • 我和你在同一条船上——我是 C# Razor 的新手,似乎无法弄清楚 Request.QueryString 为何不起作用。我已经搜索了两个多小时,但似乎找不到所需的集合,以及可用于评估查询字符串属性的各种方法。我看到(和尝试过)的所有东西都不起作用,因为它在当前上下文中不存在。

标签: c# iis-7 cgi request.querystring


【解决方案1】:

HttpContext.Current.Request 在控制台应用程序中不可用。

使用 args 参数接收查询字符串参数,如下所示。

for (int i = 0; i < args.Length; i++)
{
    Console.WriteLine("parameter[{0}] is [{1}]", i, args[i]);
}

您可能需要使用以下代码从 args 中收到的 url 中提取参数。

var url=args[0];

var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)

【讨论】:

  • 感谢您为我指明了正确的方向。不幸的是,根据您的建议,args 的长度为 0,因此我的 IIS 在查询字符串到达​​应用程序之前对其进行了过滤,或者在我的代码中仍有一些其他问题有待发现。
【解决方案2】:

这就是我最终让它工作的方式,请记住这不是经过专业验证的代码,更多的是尝试和尝试......

using System;
using System.Data;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string email = Request.QueryString["email"] ?? "null";
        if (email != "null") {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2022-01-07
    相关资源
    最近更新 更多