Read Post Data submitted to ASP.Net Form

daveywc picture daveywc · Feb 19, 2009 · Viewed 222.6k times · Source

I have a working login form in an asp.net application. Standard stuff with a username and password text box and a button to process the login. Works fine.

I have a new requirement to allow the user to input the username and password from a separate plain html page that is not a part of my asp.net application. I plan on achieving this using standard html - form, input, submit button etc. The form action will be the URL of my asp.net login page and its method will be POST.

What I want to do in the C# code behind page of the asp.net login form, presumably in the Page_Load event, is to check if the request for the page contains a username and password value being passed in. If it does then I need to read those values and process the login as if someone had clicked the login button on the asp.net page. If not then I will display the login form as usual.

How do I check for the existence of, and read, the username and password values in the request for my page.

Answer

Cerebrus picture Cerebrus · Feb 19, 2009

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.