通过jQuery和C#分别实现对.NET Core Web Api的访问以及文件上传
建立请求模型
1
2
3
4
5
6
7
|
public class UserInfo { public int Age { get ; set ; } public string Name { get ; set ; } public bool Sex { get ; set ; } public Guid Id { get ; set ; } } |
建立控制器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AspNetCore.Api.Controllers { [Route( "api/[controller]/[action]" )] [ApiController] public class DefaultController : ControllerBase { /// <summary> /// 用户信息 /// </summary> public static UserInfo UserInfo = new UserInfo { Id = Guid.NewGuid(), Age = 23, Name = "Jon" , Sex = true }; [HttpGet] public IActionResult Test() { return new JsonResult( "OK" ); } /// <summary> /// API GET /// </summary> /// <returns></returns> [HttpPost] public ActionResult<UserInfo> GetUser([FromBody]UserInfo user) { return new JsonResult(user); } /// <summary> /// API POST /// </summary> /// <returns></returns> [HttpPost] public ActionResult<UserInfo> Upload() { var files = Request.Form.Files; return new JsonResult($ "Read {string.Join(Environment.NewLine,files.Select(x=>x.FileName))} Success !" ); } } } |
建立.NET Core Web项目
建立控制器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
|
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using AspNetCore.Web.Models; using Microsoft.Extensions.Caching.Memory; using System.IO; using Microsoft.AspNetCore.Http; using System.Threading; using System.Net.Http; using System.Net; namespace AspNetCore.Web.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly IMemoryCache _cache; public HomeController(ILogger<HomeController> logger, IMemoryCache cache) { _logger = logger; _cache = cache; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true )] public IActionResult Error() { return View( new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } /// <summary> /// 上传文件 /// </summary> /// <returns></returns> [RequestSizeLimit(1_073_741_824)] public IActionResult Upload() { var url = "http://localhost:9001/Api/Default/Upload" ; var data = new MultipartFormDataContent(); if (Request.HasFormContentType) { var request = Request.Form.Files; foreach ( var item in request) { data.Add( new StreamContent(item.OpenReadStream()), item.Name, item.FileName); } foreach ( var item in Request.Form) { data.Add( new StringContent(item.Value), item.Key); } } string jsonString = string .Empty; using ( var client = new HttpClient( new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip })) { var taskResponse = client.PostAsync(url, data); taskResponse.Wait(); if (taskResponse.IsCompletedSuccessfully) { var taskStream = taskResponse.Result.Content.ReadAsStreamAsync(); taskStream.Wait(); using ( var reader = new StreamReader(taskStream.Result)) { jsonString = reader.ReadToEnd(); } } } return new JsonResult(jsonString); } /// <summary> /// 保存文件 /// </summary> /// <returns></returns> [HttpPost] [RequestSizeLimit(1_073_741_824)] public async Task<IActionResult> Save() { Stopwatch sw = new Stopwatch(); sw.Start(); var form = await Request.ReadFormAsync(); int saveCount = 0; long totalCount = form.Files.Sum(x => x.Length); foreach ( var item in form.Files) { var fileSavePath = Environment.CurrentDirectory + "\\Files\\" + item.Name; using (FileStream fs = new FileStream(fileSavePath, FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fs)) { using (BinaryReader br = new BinaryReader(item.OpenReadStream())) { var customReadLength = item.Length; byte [] buffer = new byte [customReadLength]; int readCount = 0; while ((readCount = br.Read(buffer, 0, buffer.Length)) > 0) { bw.Write(buffer, 0, readCount); saveCount += readCount; var progress = (saveCount * 1.0 / totalCount).ToString( "0.00" ); _cache.Set< string >( "UploadSpeed" , progress, DateTimeOffset.Now.AddMinutes(60)); Thread.Sleep(1000); } } } } } sw.Stop(); return new JsonResult($ "Read {string.Join(Environment.NewLine, Request.Form.Files.Select(x => x.FileName))} Success !耗时:{sw.ElapsedMilliseconds}" ); } /// <summary> /// 读取进度 /// </summary> /// <returns></returns> public IActionResult UploadProgress() { var progress = _cache.Get< string >( "UploadSpeed" ); return Json(progress); } } } |
目录结构
设置解决方案为多个项目启动
一、使用jQuery Ajax访问
(一)、表单传参( [FromForm])
数据类型:Object
ContenyType类型:application/x-www-form-urlencoded
1
|
var model = { name: "刘大大" , age: 23, sex: true }; |
前台请求
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var model = { name: "刘大大" , age: 23, sex: true }; $.ajax({ url: "http://localhost:9001/API/Default/FormCall" , type: "POST" , async: true , dataType: "json" , data: model, contentType: "application/x-www-form-urlencoded" , success: function (data) { console.log( "data:" ); console.log(data); } }); |
(二)、JSON字符串[FromBdy]
数据类型:Json
ContenyType类型:application/json
1
|
var json = '{"name":"刘大大","age":23,"sex":true}' ; |
也可以使用JSON.stringify(Object)将Object转换为JSON字符串
前端请求
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var model = { name: "刘大大" , age: 23, sex: true }; $.ajax({ url: "http://localhost:9001/API/Default/BodyCall" , type: "POST" , async: true , dataType: "json" , data: JSON.stringify(model), contentType: "application/json" , success: function (data) { console.log( "data:" ); console.log(data); } }); |
(三)、文件上传
建立FormData对象
数据类型:FromData
ContenyType类型false, //必须false才会避开jQuery对 formdata 的默认处理 processData类型: false, //必须false才会自动加上正确的Content-Type
1
|
<input type= "file" multiple id= "file" /> |
JS获取文件对象
1
2
3
4
5
6
7
|
var file = document.getElementById( "file" ); var files = file.files; var formData = new FormData(); for ( var i = 0; i < files.length; i++) { formData.append(files[i].name, files[i]); } formData.append( "name" , "刘大大" ); //可追加参数 |
AJAX请求
1
2
3
4
5
6
7
8
9
10
11
12
|
$.ajax({ url: "http://localhost:9001/API/Default/Upload" , type: "POST" , async: true , dataType: "json" , data: formData, contentType: false , processData: false , success: function (data) { console.log(data); } }); |
完整HTML源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
< div class="text-center"> < h1 class="display-4">Welcome</ h1 > < p >Learn about < a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</ a >.</ p > </ div > < div > < input type="button" id="fromform" value="Form传参" />< hr /> < input type="button" id="frombody" value="Body传参" />< hr /> < input type="file" multiple id="file" name="上传文件" />< hr /> </ div > < script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.js"></ script > < script > /** * FromForm * */ var fromform = document.getElementById("fromform"); $(fromform).click(function () { var url = 'http://localhost:9001/API/Default/FormCall'; var model = { name: "刘大大", age: 23, sex: true }; $.ajax({ url: url, type: "POST", async: true, data: model, contentType: "application/x-www-form-urlencoded", success: function (data) { console.log(data); alert(JSON.stringify(data)); }, error: function (result) { console.log(result); } }); }); /** * FromBody * */ $('#frombody').click(function () { var url = 'http://localhost:9001/API/Default/BodyCall'; var json = '{"name":"刘大大","age":23,"sex":true}'; $.ajax({ url: url, type: "POST", async: true, data: json, contentType: "application/json", success: function (data) { console.log(data); alert(JSON.stringify(data)); }, error: function (result) { console.log(result); } }); }); /** * FormData * */ var file = document.getElementById("file"); file.onchange = function () { var file = document.getElementById("file"); var files = file.files; var formData = new FormData(); for (var i = 0; i < files.length ; i++) { formData.append(files[i].name, files[i]); } formData.append("name", "刘大大"); var isUploadByJs = true; var url = isUploadByJs ? 'http://localhost:9001/API/Default/Upload' : 'http://localhost:9002/Home/Upload'; $.ajax({ url: url, type: "POST", async: true, dataType: "json", data: formData, contentType: false, //必须false才会避开jQuery对 formdata 的默认处理 processData: false, //必须false才会自动加上正确的Content-Type headers: { ReadTime: Date.now() }, beforeSend: function (xhr) { xhr.setRequestHeader('Author', 'liudada'); }, success: function (data) { console.log(data); alert(JSON.stringify(data)); }, error: function (result) { console.log(result); } }); } </script> |
二、使用C#后台访问
(一)、Get访问
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
var url = "http://localhost:57954/API/Default/Test" ; using ( var client = new HttpClient( new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip })) { var taskResponse = client.GetAsync(url); taskResponse.Wait(); if (taskResponse.IsCompletedSuccessfully) { var taskStream = taskResponse.Result.Content.ReadAsStreamAsync(); taskStream.Wait(); using ( var reader = new StreamReader(taskStream.Result)) { jsonString = reader.ReadToEnd(); } } } |
(二)、Post访问
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
var url = "http://localhost:57954/API/Default/BodyCall" ; var data = new {name= "刘大大" ,age=23,sex= true }; using ( var client = new HttpClient( new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip })) { var jsonToSend = JsonConvert.SerializeObject(data, Formatting.None, new IsoDateTimeConverter()); var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json" ); var taskResponse = client.PostAsync(url, body); taskResponse.Wait(); if (taskResponse.IsCompletedSuccessfully) { var taskStream = taskResponse.Result.Content.ReadAsStreamAsync(); taskStream.Wait(); using ( var reader = new StreamReader(taskStream.Result)) { jsonString = reader.ReadToEnd(); } } } |
(三)、上传文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
/// <summary> /// 上传文件 /// </summary> /// <returns></returns> [RequestSizeLimit(1_073_741_824)] public IActionResult Upload() { var url = "http://localhost:9001/Api/Default/Upload" ; var data = new MultipartFormDataContent(); if (Request.HasFormContentType) { var request = Request.Form.Files; foreach ( var item in request) { data.Add( new StreamContent(item.OpenReadStream()), item.Name, item.FileName); } foreach ( var item in Request.Form) { data.Add( new StringContent(item.Value), item.Key); } } string jsonString = string.Empty; using ( var client = new HttpClient( new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip })) { var taskResponse = client.PostAsync(url, data); taskResponse.Wait(); if (taskResponse.IsCompletedSuccessfully) { var taskStream = taskResponse.Result.Content.ReadAsStreamAsync(); taskStream.Wait(); using ( var reader = new StreamReader(taskStream.Result)) { jsonString = reader.ReadToEnd(); } } } return new JsonResult(jsonString); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2015-11-09 js打印的两种方法