转换FormCollection&& HttpRequest到Hashtable

时间:2017-09-25 10:34:27

标签: c# asp.net

我有两个功能,一个接收FormCollection,另一个接收HttpRequest,如下所示:

public void SetUrlParameters(FormCollection request, string controllerName = "")
{
    string sessionID = ConvertToString(request["sessionID"]);
    string idSession = ConvertToString(request["idSession"]);
    string sessionid = ConvertToString(request["sessionid"]);

    if (idSession.Length > 0)
        this.sessionID = idSession;
    else if (sessionid.Length > 0)
        this.sessionID = sessionid;
    else
        this.sessionID = sessionID;

}

private void SetUrlParameters(HttpRequest request, string controllerName = "")
{

    string sessionID = ConvertToString(request["sessionID"]);
    string idSession = ConvertToString(request["idSession"]);
    string sessionid = ConvertToString(request["sessionid"]);

    if (idSession.Length > 0)
        this.sessionID = idSession;
    else if (sessionid.Length > 0)
        this.sessionID = sessionid;
    else
        this.sessionID = sessionID;

}

private string ConvertToString(object obj, string defaultValue = "")
{
      if (obj == null) return defaultValue;

      return Convert.ToString(filterSameVariablesValue(obj));
}

正如您所看到的,这两个函数完全相同。唯一的区别是每个人接收的价值类型。

这两项功能都有效。我想要的是避免在两个函数中重复使用代码。

有什么方法可以将它折叠成一个功能?例如,将FormCollectionHttpRequest转换为Hashtable并使用它?

2 个答案:

答案 0 :(得分:2)

您可以简单地期望NameValueCollection参数对两种类型都是(几乎)共同的:

private void SetUrlParameters(NameValueCollection data, string controllerName = "")
{
    string sessionID = ConvertToString(data["sessionID"]);
    string idSession = ConvertToString(data["idSession"]);
    string sessionid = ConvertToString(data["sessionid"]);

    if (idSession.Length > 0)
        this.sessionID = idSession;
    else if (sessionid.Length > 0)
        this.sessionID = sessionid;
    else
        this.sessionID = sessionID;
}

HttpRequest的用法:

SetUrlParameters(request.Params);

FormCollection的用法:

SetUrlParameters(formCollection);

请参阅MSDN

答案 1 :(得分:0)

FormCollection继承自NameValueCollectionHttpRequest具有HttpRequest.Form属性NameValueCollection。因此,您可以使用转换为NameValueCollection

来避免重复
public void GetParameters(FormCollection form, HttpRequest request)
{
    var parameters = Convert(form);
    parameters = Convert(request.Parameters);
}

public YourParameters Convert(NameValueCollection form)
{
    //your code here
}