C# WebAPI with HttpWebRequest, HttpWebResponse and HttpContext Example

Send HttpWebRequest POST from the client to the server:

private string SendDatawithJson(Job job)
        {
            string jsonString = JsonConvert.SerializeObject(job);
            //url get it from config
            string url = "http://dasep.azurewebsites.net/api/API/CreateJob";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/json; charset=utf-8";
            request.Method = "POST";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(jsonString);
                streamWriter.Flush();
            }
            //System.Diagnostics.Debug.WriteLine("there");
            //return "";
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }


Process the HttpWebRequest POST in the server end:

[HttpPost]
        public string CreateJob()
        {
            string jobstring = "";

            HttpContext _context = HttpContext.Current;
            Stream stream = _context.Request.InputStream;
            StreamReader sr = new StreamReader(stream);
            jobstring = sr.ReadToEnd();

            Job job = JsonConvert.DeserializeObject<Job>(jobstring);

            JobRepository jobRepo = new JobRepository();
            if (jobRepo.Find(job.JobId) != null)
                return "2";

            job.CurrStatus = 0;
            job.StartDate = DateTime.Now;
            job.LastUpdate = DateTime.Now;
            job.TrackingNo = "";
            job.ActShipDate = Convert.ToDateTime("01-01-1900");
            bool result = jobRepo.Add(job) && this.AddJobCount(job.UserId);

            if (result)
            {
                //Add the pending status to the status table for the new job
                JobController jc = new JobController();
                bool statusResult = jc.AddStatus(StatusCode.CODE_PENDING, job.JobId);
                if (statusResult)
                {
                    //Send an email to reminder the printer that there is a new job
                    SendCreateJobEmail(job);
                    return "1";
                }
            }
            return "0";
        }


Send HttpWebRequest GET from the client to the server, and process the returned Json string:

public string GetPrintersForAjax() {
            string url = "http://dasep.azurewebsites.net/api/API/GetPrinters";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/json; charset=utf-8";
            request.Method = "Get";

            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                System.Diagnostics.Debug.WriteLine("Before replace: " + result);
                JavaScriptSerializer js = new JavaScriptSerializer();

                //The automatically added "" and \ need to be removed, otherwise it is not a valid json string.
                result = result.Replace("\"[", "[").Replace("]\"", "]").Replace("\\", "");
                System.Diagnostics.Debug.WriteLine("After replace: " + result);

                PrinterInfo[] pis = js.Deserialize<PrinterInfo[]>(result);

                //System.Diagnostics.Debug.WriteLine(printerInfo.PrinterLocation);
                foreach (PrinterInfo item in pis)
                {
                    System.Diagnostics.Debug.WriteLine(item.PrinterName);
                }
                return result;
            }

Process the HttpWebRequest GET in the server end:
public string GetPrinters() {
            List<ExtraUserInfo> list = new List<ExtraUserInfo>();
            ExtraUserInfoRepository repo = new ExtraUserInfoRepository();
            IQueryable<ExternalPrinter.Models.ExtraUserInfo> ei = repo.LoadAll();
            System.Diagnostics.Debug.WriteLine("Count: " + ei.Count());

            List<PrinterInfo> printerList = new List<PrinterInfo>();

            foreach (ExtraUserInfo item in ei){
                System.Diagnostics.Debug.WriteLine(item.PrinterLocation);
                printerList.Add(new PrinterInfo { Id = item.Id, JobCount = item.JobCount, PrinterLocation = item.PrinterLocation, PrinterName = item.PrinterName });
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            var json = js.Serialize(printerList);
            return json;
        }

References:

http://stackoverflow.com/questions/3307492/how-do-i-get-a-request-object-outside-a-controller-in-asp-net-mvc2

http://www.jb51.net/article/28401.htm

http://www.111cn.net/net/net/41799.htm

http://www.xuebuyuan.com/405556.html

http://www.cnblogs.com/willpan/archive/2011/09/26/2176475.html

http://fromjami.wordpress.com/2013/05/26/call-restful-service-using-httpwebrequest-and-post-data/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值