質問

私がしばしば利用 Request.QueryString[] 変数.

私の Page_load 私はよくないようなもの:

       int id = -1;

        if (Request.QueryString["id"] != null) {
            try
            {
                id = int.Parse(Request.QueryString["id"]);
            }
            catch
            {
                // deal with it
            }
        }

        DoSomethingSpectacularNow(id);

もう少し無骨やごみ.う対応しようと考えておられるのご Request.QueryString[]s?

役に立ちましたか?

解決

以下は、このようなコードを書くことができます拡張メソッドです。

int id = request.QueryString.GetValue<int>("id");
DateTime date = request.QueryString.GetValue<DateTime>("date");

これは、変換を実行するためにTypeDescriptorを使用しています。あなたのニーズに基づいて、あなたの代わりに例外をスローのデフォルト値をとるオーバーロードを追加することができます:

public static T GetValue<T>(this NameValueCollection collection, string key)
{
    if(collection == null)
    {
        throw new ArgumentNullException("collection");
    }

    var value = collection[key];

    if(value == null)
    {
        throw new ArgumentOutOfRangeException("key");
    }

    var converter = TypeDescriptor.GetConverter(typeof(T));

    if(!converter.CanConvertFrom(typeof(string)))
    {
        throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));
    }

    return (T) converter.ConvertFrom(value);
}

他のヒント

の代わりにtry-catchブロックを取り除くために使用int.TryParseます:

if (!int.TryParse(Request.QueryString["id"], out id))
{
  // error case
}

この男を試してみてください...

List<string> keys = new List<string>(Request.QueryString.AllKeys);

次に、あなたは...

を経由して実際の使いやすい文字列の男を検索できるようになります
keys.Contains("someKey")

私は少しヘルパーメソッドを使用しています:

public static int QueryString(string paramName, int defaultValue)
{
    int value;
    if (!int.TryParse(Request.QueryString[paramName], out value))
        return defaultValue;
    return value;
}

この方法は、私は、次のようにクエリ文字列から値を読み取ることができます:

int id = QueryString("id", 0);

まあ、一つのことではなくint.TryParse使用のために...

int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
    id = -1;
}

これは「存在しない」コースの「ない整数」と同じ結果を有するべきであることを前提としています。

EDIT:あなたはとにかく文字列としてリクエストパラメータを使用するつもりだときに、他のケースでは、私はそれは、彼らが存在していることを検証するために間違いなく良いアイデアだと思います。

あなたにも以下の拡張メソッドを使用して、次のように行うことができます。

int? id = Request["id"].ToInt();
if(id.HasValue)
{

}

//拡張メソッド

public static int? ToInt(this string input) 
{
    int val;
    if (int.TryParse(input, out val))
        return val;
    return null;
}

public static DateTime? ToDate(this string input)
{
    DateTime val;
    if (DateTime.TryParse(input, out val))
        return val;
    return null;
}

public static decimal? ToDecimal(this string input)
{
    decimal val;
    if (decimal.TryParse(input, out val))
        return val;
    return null;
}
if(!string.IsNullOrEmpty(Request.QueryString["id"]))
{
//querystring contains id
}

EEEEこれはカルマのリスク...

レガシー変換中に保つためにあまりにも多くのクエリ文字列変数があったので

私は、DRYユニット・テスト可能な抽象化だけでなく、理由があります。

以下のコードは、そのコンストラクタNameValueCollectionの入力(this.source)を必要と文字配列「キー、」レガシーアプリケーションは、有機むしろであり、潜在的であることが、いくつかの異なる文字列の可能性を開発していたからであるユーティリティ・クラスからのものです入力キー。しかし、私は一種の拡張性を好みます。このメソッドは、キーのコレクションを検査し、必要なデータ型で返します。

private T GetValue<T>(string[] keys)
{
    return GetValue<T>(keys, default(T));
}

private T GetValue<T>(string[] keys, T vDefault)
{
    T x = vDefault;

    string v = null;

    for (int i = 0; i < keys.Length && String.IsNullOrEmpty(v); i++)
    {
        v = this.source[keys[i]];
    }

    if (!String.IsNullOrEmpty(v))
    {
        try
        {
            x = (typeof(T).IsSubclassOf(typeof(Enum))) ? (T)Enum.Parse(typeof(T), v) : (T)Convert.ChangeType(v, typeof(T));
        }
        catch(Exception e)
        {
            //do whatever you want here
        }
    }

    return x;
}

私は実際に私のために、「面倒な作業」のすべてを行いいる、セッションを「ラップ」するためにジェネリックを使用するユーティリティクラスを持って、私はまたのQueryString値を操作するためのほぼ同じものを持っています。

このは(多くの場合、多くの)チェックのコードデュープを削除することができます..

public class QueryString
{
    static NameValueCollection QS
    {
        get
        {
            if (HttpContext.Current == null)
                throw new ApplicationException("No HttpContext!");

            return HttpContext.Current.Request.QueryString;
        }
    }

    public static int Int(string key)
    {
        int i; 
        if (!int.TryParse(QS[key], out i))
            i = -1; // Obviously Change as you see fit.
        return i;
    }

    // ... Other types omitted.
}

// And to Use..
void Test()
{
    int i = QueryString.Int("test");
}

注:

これは明らかにそれがテストコードに影響を与えることができる方法の..あなたは簡単にインスタンスとあなたが必要とするすべてのインターフェイスに基づいた作品何かにリファクタリングすることができますので、一部の人は好きではない静の使用を作る..私はちょうど考えます静力学の例では最軽量です。

ホープこのことができます/思考の糧を与えます。

い機能のための各実で小さなクラスをふんだんに使った統計):

  • GetIntegerFromQuerystring(val)
  • GetIntegerFromPost(val)
  • ....

い場合は-1を返します失敗でもOKだから、帰れなかった私にとっても、他の機能のために負の数として).

Dim X as Integer = GetIntegerFromQuerystring("id")
If x = -1 Then Exit Sub

:paramはあなたの提示が存在しないと、あなたがNULL可能タイプを指定した場合、それがnullを返すように

私はブライアン・ワッツ答えを修正しました

public static T GetValue<T>(this NameValueCollection collection, string key)
    {
        if (collection == null)
        {
            return default(T);
        }

        var value = collection[key];

        if (value == null)
        {
           return default(T);
        }

        var type = typeof(T);

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            type = Nullable.GetUnderlyingType(type);
        }

        var converter = TypeDescriptor.GetConverter(type);

        if (!converter.CanConvertTo(value.GetType()))
        {
            return default(T);
        }

        return (T)converter.ConvertTo(value, type);
    }

あなたは今、これを行うことができます:

Request.QueryString.GetValue<int?>(paramName) ?? 10;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top