简体   繁体   中英

Getting C# Request.Form in a separate class

I'm writing a C# helper to parse a HTML POST and create a signed string. The string is used in a secondary form hidden input. How can I access Request.Form fields in a static C# method? HttpWebResponse ? using System.Web.UI.Page ?

public static string cyberSourceCheckoutHtml()
{
    List<string> _string = new List<string>();
    IDictionary<string, string> parameters = new Dictionary<string, string>();
    try
    {
        if (Request.Form.AllKeys.Length > 0)
        {
            foreach (var key in form.AllKeys)
            {
                _string.Add("<input type=\"hidden\" id=\"" + key + "\" name=\"" + key + "\" value=\"" + Request.Params[key] + "\"/>\n");
                parameters.Add(key, Request.Params[key]);
            }
        }
        string sig = Corbis.Web.UI.CheckoutV2.Helpers.CybersourceSecureAcceptance.sign(parameters); 
        _string.Add("<input type=\"hidden\" id=\"signature\" name=\"signature\" value=\"" + sig + "\"/>\n");
        //<form action="https://testsecureacceptance.cybersource.com/silent/pay" method="post"/>
        return _string.ToString(); 
    }
    catch
    {
        return "";
    }
}

You have 2 options:

  • a cleaner and preferred option to get web related data into non-web related classes is to pass them as their non-web type.

eg the Request.Form data is nothing but a NameValueCollection. so you can have the method like

public static string cyberSourceCheckoutHtml(NameValueCollection formData)
{
 // use formData instead of Request.Form
}
  • option #2 is to use the Static Helper properties, provided in System.Web namespace to access the request.

    NameValueCollection formData = HttpContext.Current.Request.Form;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM