https://blog.csdn.net/xcymorningsun/article/details/53019425
最近要做后台数据接收,因为前台传来的数据太过于混乱,所以总结了一下前台数据post请求方法,顺便写了下相对应的后台接收方法。
前台主要的contenttype为下面三种:(需要注意的是请求头中datatype与contenttype的区别,datatype是要求浏览器返回的数据格式,这里的contenttype指的是提交的数据格式)
应用情景:
- multipart/form-data类型主要是上传文件时用到;
- application/x-www-form-urlencoded类型主要是提交k-v时用到,当然这种方法也可以将json设置在v中提交json数据;
- application/json类型主要是传递json数据用到,层次比较深的数据;
post提交主要就是依赖于浏览器表单提交和ajax方式提交,两者对这三种方式都可以实现,下面分别介绍这两类方法:
一、Form表单实现(不含后端)
1、application/x-www-form-urlencoded方法
- <form action="Handler2.ashx" method="post" enctype="application/x-www-form-urlencoded">
- <p>客户名称: <input type="text" name="CustomerName" style=" 300px" /></p>
- <p>客户电话: <input type="text" name="CustomerTel" style=" 300px" /></p>
- <p><input type="submit" value="提交" /></p>
- </form>
2、multipart/form-data方法
- <p>要上传的文件1<input type="file" name="file1"/></p>
- <p>要上传的文件2<input type="file" name="file2"/></p>
- <p><input type="submit" value="提交" /></p>
- </form>
3、json方法
3.1 form表单数据可以直接json序列化var queryArray = $(formElement).serializeArray();
3.2 也可以在k-v中的v中添加实际值,当然这个违背了form表单多个k-v的初衷,但是也可以实现
二、ajax实现(含后端)
1、application/x-www-form-urlencoded方法(json与kv)
- var data={ "books": [ { "language":"Java" , "edition":"second" }, { "language":"C++" , "lastName":"fifth" }, { "language":"C" , "lastName":"third" } ] }
- $.ajax({
- type: "post",
- url: "http://localhost:39870/api/test/getUrlencode",
- contentType : "application/x-www-form-urlencoded; charset=UTF-8",
- data: { books: JSON.stringify(data), txtPass: "123" },
- success: function (res) {
-
- //alert(res);
- //layer.close(ii);
- }
- });
- [HttpPost]
- public IHttpActionResult getFormdata()
- {
-
- string id = HttpContext.Current.Request["id"];
- string name = HttpContext.Current.Request["name"];
-
- return Ok("success2");
- }
用上述方法既可以获取简单的kv数据,也可以自己拼接类json数据,不过其中的数据都是默认在浏览器服务器进行url编码解码。可以用下面方法实验得出:
- HttpRequest request = HttpContext.Current.Request;
- Stream stream = request.InputStream;
- StreamReader streamReader = new StreamReader(stream);
- string json = string.Empty;
- json = streamReader.ReadToEnd();
- json = HttpUtility.UrlDecode(json);
"books=%7B%22books%22%3A%5B%7B%22language%22%3A%22Java%22%2C%22edition%22%3A%22second%22%7D%2C%7B%22language%22%3A%22C%2B%2B%22%2C%22lastName%22%3A%22fifth%22%7D%2C%7B%22language%22%3A%22C%22%2C%22lastName%22%3A%22third%22%7D%5D%7D&txtPass=123"
进行编码后数据为:
"books={"books":[{"language":"Java","edition":"second"},{"language":"C++","lastName":"fifth"},{"language":"C","lastName":"third"}]}&txtPass=123"
2、multipart/form-data方法
- var data = new FormData();
- var files = $("#fileUpload").get(0).files;
- data.append("id","001");
- var name={ "books": [ { "language":"Java" , "edition":"second" }, { "language":"C++" , "lastName":"fifth" }, { "language":"C" , "lastName":"third" } ] };
- data.append("name",JSON.stringify(name));
- if(files.length > 0){
- for (var i = 0; i < files.length;i++){
- data.append(i.toString(), files[i]);
- }
- }
- $.ajax({
- type: "post",
- url: "http://localhost:39870/api/test/getFormdata",
- contentType: false,
- cache: false,
- currentType: false,
- processData: false,
- data: data,
- success: function (res) {
-
- //alert(res);
- }
- });
后台获取数据
- string id=HttpContext.Current.Request["id"];
- string name = HttpContext.Current.Request["name"];
- HttpFileCollection files = HttpContext.Current.Request.Files;
-
- foreach (string key in files.AllKeys)
- {
- HttpPostedFile file = files[key];
- if (string.IsNullOrEmpty(file.FileName) == false)
- {
-
- string path = HttpContext.Current.Server.MapPath("~/App_Data/") + file.FileName;
- string path2 = HttpContext.Current.Request.Url.Authority+"/" + file.FileName;
- string path3 = "C:/Users/xcy/Desktop/金阁寺需求分析/" + file.FileName;
- file.SaveAs(path3);
- }
- }
此种方法可以接受kv数据,类json数据和文件,数据并未进行url编码。可以用下面方法验证:
- HttpRequest request = HttpContext.Current.Request;
- Stream stream = request.InputStream;
- StreamReader streamReader = new StreamReader(stream);
- string json = string.Empty;
- json = streamReader.ReadToEnd();
- json = HttpUtility.UrlDecode(json);
"------WebKitFormBoundaryB4I0wChQCc6LwykM
Content-Disposition: form-data; name="id"
001
------WebKitFormBoundaryB4I0wChQCc6LwykM
Content-Disposition: form-data; name="name"
{"books":[{"language":"Java","edition":"second"},{"language":"C++","lastName":"fifth"},{"language":"C","lastName":"third"}]}
------WebKitFormBoundaryB4I0wChQCc6LwykM--
"
进行url编码之后没有变化,为:
"------WebKitFormBoundaryB4I0wChQCc6LwykM Content-Disposition: form-data; name="id" 001 ------WebKitFormBoundaryB4I0wChQCc6LwykM Content-Disposition: form-data; name="name" {"books":[{"language":"Java","edition":"second"},{"language":"C ","lastName":"fifth"},{"language":"C","lastName":"third"}]} ------WebKitFormBoundaryB4I0wChQCc6LwykM-- "
3、json方法
- var data={"books":[{"language":"Java","edition":"second"},{"language":"C++","lastName":"fifth"},{"language":"C","lastName":"third"}]};
- $.ajax({
- type: "post",
- url: "http://localhost:39870/api/test/gettest3",
- contentType: "application/json; charset=utf-8",
- cache: false,
- data: JSON.stringify(data),
- success: function (res) {
-
- }
- });
注意JOSN.stringify(),不添加都会失败,直接传的是url编码后的原字符串。这里插播一下字符串与对象转换
JSON.stringify(obj)将JSON转为字符串。
JSON.parse(string)将字符串转为JSON格式
例子:
- var a={"name":"tom","sex":"男","age":"24"};
-
- var b='{"name":"Mike","sex":"女","age":"29"}';
-
- var aToStr=JSON.stringify(a);
-
- var bToObj=JSON.parse(b);
-
- alert(typeof(aToStr)); //string
-
- alert(typeof(bToObj));//object
看完后就知道为什么要用JSON.stringify(obj)了,因为我们要穿的是字符串,而代码中data变量原来是js对象,so要变一下啦
而且JSON.stringify()会自动添加转义符,比如我们在一个字段包含"或者的时候,如下:
- var temp={
- "F_CODE": "001",
- "F_REGION_CODE": "001",
- "F_ZTPG": "小"东哥很'",
- "F_PGZS": "string",
- "F_PIC": "string",
- "F_FILE": "string",
- "F_TYPE": "string",
- "F_PROJECT_CODE": "string",
- "F_TIME": "2017-05-24T03:23:11.555Z"
- };
- var tt=JSON.stringify(temp);
temp显示的时候会不显示转义符,当用stringify处理后会的字符串上传到后端的时候会出现转义符,使得上传数据不会出错
后台接收方法
3.1
- public IHttpActionResult getTest4([FromBody]object jdata)
- {
- //dynamic
- return Ok("ddd");
- }
前台的contenttype必须设置为json,此为WebAPI的方式,这种方式添加FromBody这个参数,会针对contenttype为json的post请求自动拦截,如果当contenttype不为json,则会影响后面stream正常获取,即:如果在上面代码中添加楼下的代码,在下面的代码中是获取不到json数据的===
3.2
- HttpRequest request = HttpContext.Current.Request;
- Stream stream = request.InputStream;
- StreamReader streamReader = new StreamReader(stream);
- string json = string.Empty;
- json = streamReader.ReadToEnd();
这种方法在前两种的方法中已经提到过,用stream的方式获取方法比较通用,这个方法是万能的,v5===
后来想了想还是request是王道,其他的好多都是在他基础上扩展的,目前知道request主要有流和参数获取两种
===============================================================================================
有小伙伴们问get请求的事儿,顺便写了下
第一种:json对象
- $(document).ready(function(){
- var data={
- "F_CODE": "1",
- "F_NAME": "xcy"
- };
- $.ajax({
- type: "get",
- url: "http://localhost:27110/test/formbody",
- cache: false,
- data: data,
- success: function (res) {
-
- }
- });
-
- });
第二种:url
- $(document).ready(function(){
- $.ajax({
- type: "get",
- url: "http://localhost:27110/test/formbody?F_CODE=1&&F_NAME=xcy",
- cache: false,
- data: data,
- success: function (res) {
-
- }
- });
-
- });
这里一定要将data里面设置为json对象,不要json.stringify加工,这样才能放到url链接后面,不然直接把json字符串放进去了,如下:
http://localhost:27110/test/formbody?{%22F_CODE%22:%221%22,%22F_NAME%22:%22xcy%22}&_=1495087390056
后台处理
第一种:与webapi无关
string name = HttpContext.Current.Request["F_CODE"];
第二种:webapi参数绑定
- [HttpGet]
- public IHttpActionResult formbody(string F_CODE)
- {
-
- return Ok(F_CODE);
- }
不是很难,注意一点的是get请求不用设置contenttype,因为contenttype是针对body的,既然body没了,contenttype自然没效果了。
总结了一天的时间来搞post前台提交后台接受问题,基本用途够了,还需进一步理解,希望大牛斧正==