C#ASP.NET查询字符串分析器 [英] C# ASP.NET QueryString parser

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

问题描述

如果你一直在寻找一个非常干净的方式来解析你的查询字符串值,我想出了这一点:

If you have been looking for a nice and clean way to parse your query string values, I have come up with this:

    /// <summary>
    /// Parses the query string and returns a valid value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key">The query string key.</param>
    /// <param name="value">The value.</param>
    protected internal T ParseQueryStringValue<T>(string key, string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            //TODO: Map other common QueryString parameters type ...
            if (typeof(T) == typeof(string))
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(int))
            {
                int tempValue;
                if (!int.TryParse(value, out tempValue))
                {
                    throw new ApplicationException(string.Format("Invalid QueryString parameter {0}. The value " +
                                                              "'{1}' is not a valid {2} type.", key, value, "int"));
                }
                return (T)Convert.ChangeType(tempValue, typeof(T));
            }
            if (typeof(T) == typeof(DateTime))
            {
                DateTime tempValue;
                if (!DateTime.TryParse(value, out tempValue))
                {
                    throw new ApplicationException(string.Format("Invalid QueryString parameter {0}. The value " +
                                                         "'{1}' is not a valid {2} type.", key, value, "DateTime"));
                }
                return (T)Convert.ChangeType(tempValue, typeof(T));
            }
        }
        return default(T);
    }

我一直想有这样的事情终于得到它的权利......至少我是这么认为的......

I have always wanted to have something like that and finally got it right ... at least I think so ...

在code应该是不言而喻的......

The code should be self explanatory ...

任何意见或建议,使其更好地为AP preciated。

Any comments or suggestions to make it better are appreciated.

推荐答案

一个简单的方法来解析(如果你不想做类型转换)是

A simple way to parse (if you dont want to do type conversions) is

 HttpUtility.ParseQueryString(queryString);

您可以提取从URL查询字符串以

You can extract querystring from a URL with

 new Uri(url).Query

这篇关于C#ASP.NET查询字符串分析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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