如何使用C#在ASP.Net中使用Web请求对象提交表单

时间:2014-04-01 11:16:30

标签: c# asp.net .net webrequest

我只想使用C#在ASP.Net中使用Web请求对象提交表单。

以下是我提交数据的控制台应用程序代码:

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());
        }
    }
}

这是我用于检索此数据的ASP.Net网站页面代码:

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();
}

但是,当我运行此应用程序时,会出现如下错误:

  

远程服务器返回错误:(500)内部服务器错误。

目前,我正在使用控制台应用程序将此数据提交给可运行的localhost网站。

请帮助我!

0 个答案:

没有答案