1

I just want to submit form using Web request object in ASP.Net with C#.

Here is my console application code for submitting data:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create web request object
            WebRequest objWebRequest;

            // Set url properties
            string url = "http://localhost:2055/EasyWeb/Admin/Post_History.aspx";
            objWebRequest = WebRequest.Create(url);
            objWebRequest.Method = "POST";

            // add sample form data
            ArrayList queryList = new ArrayList();
            queryList.Add(string.Format("{0}={1}", "title", "From Admin to All Users"));
            queryList.Add(string.Format("{0}={1}", "desc", "hi all users"));
            queryList.Add(string.Format("{0}={1}", "category", "Test"));
            queryList.Add(string.Format("{0}={1}", "touser", null));
            queryList.Add(string.Format("{0}={1}", "status", null));
            queryList.Add(string.Format("{0}={1}", "group", null));
            queryList.Add(string.Format("{0}={1}", "isfile", "False"));
            queryList.Add(string.Format("{0}={1}", "sentdatetime", DateTime.Now.ToString()));
            // Set the encoding type
            objWebRequest.ContentType = "application/x-www-form-urlencoded";
            string Parameters = String.Join("&", (String[])queryList.ToArray(typeof(string)));
            objWebRequest.ContentLength = Parameters.Length;

            // Write stream
            StreamWriter sw = new StreamWriter(objWebRequest.GetRequestStream());
            sw.Write(Parameters);
            sw.Close();

            //we get back the response after submission
            HttpWebResponse objHttpWebResponse;
            objHttpWebResponse = (HttpWebResponse)objWebRequest.GetResponse();
            StreamReader sr = new StreamReader(objHttpWebResponse.GetResponseStream());
        }
    }
}

and here is my ASP.Net website page code for retrieving this data:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Params.Keys.Count > 54)
    {
        using (DataClassesDataContext db = new DataClassesDataContext())
        {
            Session["Username"] = db.Users.Where(u => u.type_id.Equals("1")).Select(u => u.Username).FirstOrDefault();
            string title = null, desc = null, category = null, touser = null, status = null, group = null, isfile = null, sentdatetime = null;
            foreach (string strName in Request.Params)
            {
                string strValue = Request.Form[strName];
                switch (strName)
                {
                    case "title":
                        title = strValue;
                        break;
                    case "desc":
                        desc = strValue;
                        break;
                    case "category":
                        category = strValue;
                        break;
                    case "touser":
                        touser = strValue;
                        break;
                    case "status":
                        status = strValue;
                        break;
                    case "group":
                        group = strValue;
                        break;
                    case "isfile":
                        isfile = strValue;
                        break;
                    case "sentdatetime":
                        sentdatetime = strValue;
                        break;
                }
            }
            int category_id = db.Categories.Where(c => c.Category_name.Equals(category)).Select(c => c.Id).FirstOrDefault();
            int user_id = db.Users.Where(u => u.type_id.Equals("1")).Select(u => u.Id).FirstOrDefault();
            System.Nullable<int> touser_id = null;
            System.Nullable<int> status_id = null;
            System.Nullable<int> group_id = null;
            System.Nullable<DateTime> sent_datetime = null;
            if (!string.IsNullOrEmpty(touser))
            {
                touser_id = db.Users.Where(u => (u.First_name + ' ' + u.Last_name).Equals(touser)).Select(u => u.Id).FirstOrDefault();
            }
            if (!string.IsNullOrEmpty(status))
            {
                status_id = db.Status.Where(s => s.status_name.Equals(status)).Select(s => s.Id).FirstOrDefault();
            }
            if (!string.IsNullOrEmpty(group))
            {
                group_id = db.Groups.Where(g => g.Group_name.Equals(group)).Select(g => g.Id).FirstOrDefault();
            }
            bool is_file = Convert.ToBoolean(isfile);
            if (!string.IsNullOrEmpty(sentdatetime))
            {
                sent_datetime = DateTime.Parse(sentdatetime);
            }
            Post myPost = new Post();
            myPost.Title = title;
            myPost.Category_id = category_id;
            myPost.Description = desc;
            myPost.User_id = user_id;
            myPost.ToUser_id = touser_id;
            myPost.status_id = status_id;
            myPost.group_id = group_id;
            myPost.IsFileAttached = is_file;
            myPost.Sent_Datetime = sent_datetime;
            db.Posts.InsertOnSubmit(myPost);
            db.SubmitChanges();
        }
    }
    if (!Page.IsPostBack)
    {
        using (DataClassesDataContext db = new DataClassesDataContext())
        {
            var query = db.ProfileSetups.Select(p => p).ToList();
            foreach (var item in query)
            {
                GV_ViewPost.PageSize = item.Page_Size;
            }
        }
        Panel_AddNew.Visible = false;
        Panel_View.Visible = false;
        Session["CommandName"] = "Inbox";
        Session["ColumnName"] = null;
        Session["SearchtText"] = null;
        this.FillGrid(Session["CommandName"].ToString(), (String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
        Bind_DDL_Column_List();
        Bind_DDL_Category_List();
        Bind_Users_List();
    }
    this.GetData();
}

However, when I run this application an error occurs like:

The remote server returned an error: (500) Internal Server Error.

Currently I am submitting this data with Console application to runnable localhost website.

Please help me!

Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
shalin gajjar
  • 646
  • 4
  • 15
  • 44
  • 1
    You havn't url-encoded your values (spaces for example will break it) Example: `queryList.Add(string.Format("{0}={1}", "title", HttpUtility.UrlEncode("From Admin to All Users")));` – James S Apr 01 '14 at 11:35
  • it seems your page is not public, otherwise everything is OK. – akbar ali Apr 01 '14 at 11:39
  • @JamesS - what namespace have HttpUtility class for that in .net 3.5 – shalin gajjar Apr 01 '14 at 11:47
  • `HttpUtility` is in `System.Web`. Try encoding the POST parameters – Nilesh Apr 01 '14 at 12:45
  • ya already include like using system.web but it says The name 'HttpUtility' does not exist in the current context – shalin gajjar Apr 01 '14 at 12:48
  • Have you referenced the Dll (System.Web.dll) in your project? – James S Apr 01 '14 at 12:50
  • ok.ok i got it and it's works – shalin gajjar Apr 01 '14 at 12:51
  • 1
    It should be in the GAC, so you can reference it just by adding an assembly reference. The Actual assembly is probably at C:\Windows\Microsoft.NET\Framework64\v2.0.50727 (for .net3.5), although of course your windows directory may be elsewhere – James S Apr 01 '14 at 12:56
  • @JamesS - just look at my Page_Load method here i just want to check in advance that any Form.Request made from outer side or not with this statement if (Request.Params.Keys.Count > 0) is not correct. I have to deal with checking that request made from outer side. then this code error can not insert null to this table. – shalin gajjar Apr 01 '14 at 13:17
  • ok i got solution i have to set count greater than 54 then it's works. – shalin gajjar Apr 02 '14 at 06:13
  • @JamesS - how i place files to webrequest object and at page side how i retrieve it. – shalin gajjar Apr 02 '14 at 06:19
  • 1
    Look at the accepted answer to this question: [link](http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data) – James S Apr 02 '14 at 09:05

0 Answers0