利用HttpWebRequest从ASP.NET MVC 向 ASP.NET MVC Core 中传递对象

一 简介     

     HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。它们支持一系列有用的属性。这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程序来说是可访问的。请注意,HttpWebRequest对象不是利用new关键字通过构 造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。另外,你可能预计需要显式地调用一个“Send”方法,实际上不需要。接下来调用 HttpWebRequest.GetResponse()方法返回的是一个HttpWebResponse对象。你可以把HTTP响应的数据流 (stream)绑定到一个StreamReader对象,然后就可以通过ReadToEnd()方法把整个HTTP响应作为一个字符串取回。也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。

二 场景

   应公司项目需要,会员中心登录的用户,需要将登录用户信息 存储到MonogoDB中,由于 MongoDB 的相关操作已 集成到 ASP.NET Core MVC  服务中 ,在此场景中,需要将登录的用户信息,通过对象的方式 传递到服务器端,服务器端接收到传递的对象之后,利用ASP.NET Core自带的校验方式,完成实体验证.

三 具体实现

 服务器端实现:

1 创建接收实体对象:利用 Required 特性 标记该属性不能为空.

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.Linq;
 5 using System.Threading.Tasks;
 6 
 7 namespace PageViewCollection.Models.Request
 8 {
 9     public class LoginRecordRequest
10     {
11         /// <summary>
12         /// 会员ID
13         /// </summary>
14         [Required(ErrorMessage = "会员ID不能为空")]
15         public int cust_id { get; set; }
16 
17         /// <summary>
18         /// 会员类型
19         /// </summary>
20         [Required(ErrorMessage = "会员类型不能为空")]
21         public string cust_kind { get; set; }
22 
23         /// <summary>
24         /// 指纹
25         /// </summary>
26         [Required(ErrorMessage = "会员指纹不能为空")]
27         public string finger { get; set; }
28 
29         /// <summary>
30         /// 登录来源
31         /// </summary>
32         [Required(ErrorMessage = "登录来源不能为空")]
33         public string LoginSource { get; set; }
34     }
35 }

2 创建控制器,利用  ModelState.IsValid 完成实体参数验证

 1 using Microsoft.AspNetCore.Mvc;
 2 using PageViewCollection.BLL;
 3 using PageViewCollection.Entity;
 4 using PageViewCollection.Models;
 5 using PageViewCollection.Models.Request;
 6 using System;
 7 
 8 namespace PageViewCollection.Controllers
 9 {
10     /// <summary>
11     /// 用户登录数据记录接口
12     /// </summary>
13     public class LoginRecordsController : Controller
14     {
15         LoginRecordBLL RecordBLL = new LoginRecordBLL();
16         [HttpPost,Route("LoginRecores/Index")]
17         public IActionResult Index(LoginRecordRequest loginRecordRequest)
18         {
19             //验证实体
20             if (!ModelState.IsValid)
21             {
22                 string result = string.Empty;
23                 foreach (var item in ModelState.Values)
24                 {
25                     foreach (var error in item.Errors)
26                     {
27                         result += error.ErrorMessage + "|";
28                     }
29                 }
30                 return Json(ResponseModel.Succeed(result));
31             }
32 
33             //初始化数据
34 
35             LoginRecord loginRecord = new LoginRecord();
36             loginRecord.cust_id = loginRecordRequest.cust_id;
37             loginRecord.cust_kind = loginRecordRequest.cust_kind;
38             loginRecord.finger = loginRecordRequest.finger;
39             loginRecord.LoginSource = loginRecordRequest.LoginSource;
40             loginRecord.state = 1;
41             loginRecord.time = DateTime.Now;
42 
43             //插入数据
44             RecordBLL.InsertLoginRecord(loginRecord);
45 
46             return Json(ResponseModel.Succeed("成功"));
47         }
48     }
49 }

客户端实现:

1 封装 Post 提交数据的方法

 1   /// <summary> 
 2     /// 后台cs代码中发送POST请求  传值的内容加密了 PicName=123 &Pic=123
 3     /// </summary>
 4     /// <param name="url">请求url</param>
 5     /// <param name="postData">参数</param>
 6     /// <returns></returns>
 7     public static string Post(string url, string postData)
 8     {
 9         System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
10         byte[] data = encoding.GetBytes(postData);
11 
12         // Prepare web request...   编写web请求
13         //WebRequest发出url请求
14         System.Net.HttpWebRequest myRequest =
15         (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
16 
17         myRequest.Method = "POST";
18         myRequest.ContentType = "application/x-www-form-urlencoded";
19         myRequest.ContentLength = data.Length;
20         myRequest.KeepAlive = false;
21         System.IO.Stream newStream = myRequest.GetRequestStream();
22         //myRequest.BeginGetResponse(
23 
24         // Send the data.   
25         newStream.Write(data, 0, data.Length);
26         newStream.Close();
27 
28         try
29         {
30             // Get response   返回来自internet资源的响应
31             System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)myRequest.GetResponse();
32             System.IO.StreamReader reader = new System.IO.StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
33             string content = reader.ReadToEnd();
34             return content;
35         }
36         catch (Exception ex)
37         {
38             return "错误提示:" + ex.Message;
39         }
40     }

2  创建相同的传递数据实体

 1     public class LoginRecordRequest
 2     {
 3         public int cust_id { get; set; }
 4 
 5         public string cust_kind { get; set; }
 6      
 7         public string finger { get; set; }
 8 
 9         public string LoginSource { get; set; }
10     }

3 调用接口 传递数据

 注意:传递数据的拼接方式;

 /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            LoginRecordRequest loginRecord = new LoginRecordRequest();
            loginRecord.cust_id = 13456;
            loginRecord.cust_kind = "配货信息部";
            loginRecord.LoginSource = "m站";
           
            string postData = "cust_id="+loginRecord.cust_id+ "&cust_kind="+loginRecord.cust_kind+ "&finger="+loginRecord.finger + "&LoginSource="+loginRecord.LoginSource;

            string str =  PostSubmitter.Post("http://www.ceshi.com/LoginRecores/Index", postData);
 
            return View("NewIndex",model);
        }

 

posted @ 2020-05-25 20:05  小白膜拜大佬  阅读(481)  评论(0编辑  收藏  举报