转换/ ASP.NET中的访问查询字符串值 [英] Converting/accessing QueryString values in ASP.NET

查看:155
本文介绍了转换/ ASP.NET中的访问查询字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,每个人都做了处理/抽象ASP.NET中的查询字符串。在我们的一些Web应用程序我看到了很多这一切都在网站:

I'm curious what everyone does for handling/abstracting the QueryString in ASP.NET. In some of our web apps I see a lot of this all over the site:

int val = 0;
if(Request.QueryString["someKey"] != null)
{
val = Convert.ToInt32(Request.QueryString["someKey"]);
}

什么是一些更好的方法来处理这​​个粗野?

What are some better ways to handle this grossness?

推荐答案

我倾向于喜欢它们抽象为属性的想法。 例如:

I tend to like the idea of abstracting them as properties. for example:

        public int age { 
        get
        {
            if (Request.QueryString["Age"] == null)
                return 0;
            else
                return int.Parse(Request.QueryString["Age"]);                                    
        }
    }

您可以添加更多的验证,如果你想的话。但我往往喜欢包装我所有的查询字符串变量这种方式。

You could add more validation if you wanted to. But I tend to like wrapping all of my query string variables this way.

编辑:--- 另外,作为另一个海报指出,你必须建立在每一页上的这些属性。我的答案是不,你不知道。您可以创建,你可以称之为查询字符串什么的一个类这些属性。然后你就可以在你要访问您的查询字符串的每个页面实例化这个类,那么你可以简单地做这样的事情

--- Also as another poster pointed out that you have to create these properties on every page. My answer is no you do not. You can create these properties in a single class that you can call "QueryStrings" or something. Then you can instantiate this class in every page where you want to access your query strings, then you can simply do something like

var queryStrings = new QueryStrings()
var age = queryStrings.age;

这样,您就可以封装了所有的逻辑访问和处理每种类型的查询变量在一个单一的维护位置。

This way you can encapsulate all of the logic for accessing and handling each type of query variable in a single maintainable location.

EDIT2:--- 而且因为它是一个类的实例,你也可以使用依赖注入的查询字符串类在每一个你正在使用它的地方注入。 StructureMap( http://structuremap.sourceforge.net )做了一个很好的工作。这也可以让你小样的查询字符串类和注入,如果你想要做自动化单元测试。这是很容易嘲笑这件事比ASP.Net的Request对象。

--- And because it is an instance of the class, you could also use dependency injection to inject the QueryStrings class in every place you are using it. StructureMap (http://structuremap.sourceforge.net) does a good job of that. This also allows you to mock up the QueryStrings class and inject that if you wanted to do automated unit testing. It is much easier to mock this up than ASP.Net's Request object.

这篇关于转换/ ASP.NET中的访问查询字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆