【问题标题】:Read http body and put it into variables读取http body并将其放入变量中
【发布时间】:2011-01-25 07:21:48
【问题描述】:

如何创建一个类来读取 html 正文并将其转换为变量?

示例 页面http://domain.com/page1.aspx

在 html 正文内容中显示以下纯文本

item1=xyz&item2=abc&item3=jkl

如何读取 html 正文的内容并将它们分配给变量

在这种情况下

variable1=xyz(取自 item1= 的值)

variable2=abc(取自 item2= 的值)

variable3=jkl(取自 item3= 的值)?

【问题讨论】:

    标签: c# .net asp.net html


    【解决方案1】:

    我认为您的意思是查询字符串而不是 html 正文。在这种情况下,您可以使用 ASP.NET Page 类的属性 Context,如下所示

    string var1 = Context.Request.QueryString["item1"];
    

    【讨论】:

    • 谢谢,但我的意思实际上是指 html 正文,而不是查询字符串 http//domain.com/page1.aspx?item1=xyz&item2=abc&item3=jkl
    • 对不起,我现在明白了...我是这样想的,因为 item1=xyz&item2=abc&item3=jkl 看起来像查询字符串。 =)
    【解决方案2】:

    这是一个步骤的过程。

    首先您需要获取正文内容。

    其次你需要解析内容并赋值给变量。

    获取正文内容代码如下所示:

    Regex exp = new Regex(@"((?:.(?!<body[^>]*>))+.<body[^>]*>)|(</body\>.+)", RegexOptions.IgnoreCase);
    string InputText = content;
    
    string[] MatchList = exp.Split(InputText);
    string body = MatchList[2];
    

    解析代码如下:

            string body = content;
            string [] param = {"&"};
            string[] anotherParam = { "=" };
            string[] str = body.Split(param , StringSplitOptions.RemoveEmptyEntries);
            System.Collections.Hashtable table = new System.Collections.Hashtable();
            foreach (string item in table)
            {
                string[] arr = item.ToString().Split(anotherParam, StringSplitOptions.RemoveEmptyEntries);
                if(arr.length != 2)
                     continue;
                if(!table.Contains(arr[0])){
                    table.Add(arr[0], arr[1]);
                }                
            }
    

    【讨论】:

    • @Adeel:不,你没有!您的代码现在相当于没有 try/catch 块。所以,摆脱 try/catch 块。你想达到什么目的?为什么你认为你需要一个 try/catch 块?
    • @john 实际上首先我添加了带有空块的catch,然后在您的评论后重新抛出,如果查询字符串参数重复,如果再次找到相同的查询字符串参数,Add 方法将抛出异常.例如,如果 body 的内容是 x1=1&x2=2&x1=9 。比 hastable 的 Add 方法可以抛出异常(由于重复键)。所以在目前的情况下,我正在重新抛出。
    • @Adeel 在asp.net中,如果一个参数提交了两次,它只会被合并到一个中。例如。 x1=1,2&x2=2。最好检查集合是否已经包含参数,而不是让异常发生。
    • @Adeel:如果抛出异常是因为其他问题怎么办?你会隐藏另一个问题。如果您担心重复键,请在添加前检查。
    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多