通過jQuery和C#分別實現對.NET Core Web Api的訪問以及文件上傳


建立.NET Core Web Api項目

建立請求模型

    public class UserInfo
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public bool Sex { get; set; }
        public Guid Id { get; set; }
    }

建立控制器

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項目

建立控制器

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

 var model = { name: "劉大大", age: 23, sex: true };

前台請求

        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

       var json = '{"name":"劉大大","age":23,"sex":true}';

也可以使用JSON.stringify(Object)將Object轉換為JSON字符串

前端請求

        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

html

 <input type="file" multiple id="file" />

JS獲取文件對象

        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請求

 $.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源碼

<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訪問

 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訪問

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

  

(三)、上傳文件

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

  

WebHelper

這里包含了WebRequest和HttpClient兩種請求方式,以及包含了將Object對象序列化為HttpCotnent對象的方法。

/***************************************************************************************************************************************************
 * *文件名:WebHelper.cs
 * *創建人:Jon
 * *日 期 :2018年5月25日
 * *描 述 :實現HTTP協議中的GET、POST請求
 * *MVC使用HttpClient上傳文件實例:      
        public IActionResult Upload()
        {

            var url = "http://localhost:57954/API/Default/values";
            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);
                }
            }
            WebHelper.PostByHttpClientFromHttpContent(url, data);
            return Json("OK");
        }
*****************************************************************************************************************************************************/
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace Expansion.Helper
{
    public static class WebHelper
    {
        /// <summary>
        /// 通過WebRequest發起Get請求
        /// </summary>
        /// <param name="url">請求地址</param>
        /// <returns>JSON字符串</returns>
        public static string GetByWebRequest(string url)
        {
            string jsonString = string.Empty;
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/json";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            var response = (HttpWebResponse)request.GetResponse();
            using (var stream = new StreamReader(response.GetResponseStream()))
            {
                jsonString = stream.ReadToEnd();
            }
            return jsonString;
        }

        /// <summary>
        /// 通過WebRequest發起Post請求
        /// </summary>
        /// <param name="url">請求地址</param>
        /// <param name="data">請求參數</param>
        /// <returns>JSON字符串</returns>
        public static string PostByWebRequest(string url, object data)
        {
            string jsonString = string.Empty;
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "POST";
            request.Timeout = Int32.MaxValue;
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            var jsonToSend = JsonConvert.SerializeObject(data, Formatting.None, new IsoDateTimeConverter());
            byte[] btBodys = Encoding.UTF8.GetBytes(jsonToSend);
            request.ContentLength = btBodys.Length;
            request.GetRequestStream().Write(btBodys, 0, btBodys.Length);
            var response = (HttpWebResponse)request.GetResponse();
            using (var stream = new StreamReader(response.GetResponseStream()))
            {
                jsonString = stream.ReadToEnd();
            }
            return jsonString;
        }


        /// <summary>
        /// 通過HttpClient發起Get請求
        /// </summary>
        /// <param name="url">請求地址</param>
        /// <returns>JSON字符串</returns>
        public static string GetByHttpClient(string url)
        {
            string jsonString = string.Empty;
            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();
                    }
                }
            }
            return jsonString;
        }

        /// <summary>
        /// 通過HttpClient發起Post請求
        /// </summary>
        /// <param name="url">請求地址</param>
        /// <param name="data">請求參數</param>
        /// <returns>JSON字符串</returns>
        public static string PostByHttpClient(string url, object data)
        {
            string jsonString = string.Empty;
            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();
                    }
                }
            }
            return jsonString;
        }

        /// <summary>
        /// 通過數據來自HttpContent的HttpClient發起Post請求
        /// </summary>
        /// <param name="url">請求地址</param>
        /// <param name="content">請求參數</param>
        /// <returns>JSON字符串</returns>
        public static string PostByHttpClientFromHttpContent(string url, HttpContent content)
        {
            string jsonString = string.Empty;
            using (var client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }))
            {
                var taskResponse = client.PostAsync(url, content);
                taskResponse.Wait();
                if (taskResponse.IsCompletedSuccessfully)
                {
                    var taskStream = taskResponse.Result.Content.ReadAsStreamAsync();
                    taskStream.Wait();
                    using (var reader = new StreamReader(taskStream.Result))
                    {
                        jsonString = reader.ReadToEnd();
                    }
                }
            }
            return jsonString;
        }

        /// <summary>
        /// Object轉換為StreamContent
        /// </summary>
        /// <param name="data">請求參數</param>
        /// <returns>StreamContent</returns>
        public static HttpContent ToStreamContent(this object data)
        {

            var json = JsonConvert.SerializeObject(data, Formatting.None, new IsoDateTimeConverter());
            byte[] bytes = Encoding.UTF8.GetBytes(json);
            MemoryStream ms = new MemoryStream();
            ms.Write(bytes, 0, bytes.Length);
            ms.Position = 0;
            HttpContent streamContent = new StreamContent(ms);
            return streamContent;
        }

        /// <summary>
        /// Object轉換為StringContent
        /// </summary>
        /// <param name="data">請求參數</param>
        /// <returns>StringContent</returns>
        public static HttpContent ToStringContent(this object data)
        {
            HttpContent stringContent = new StringContent(JsonConvert.SerializeObject(data));
            return stringContent;
        }

        /// <summary>
        /// Object轉換為MultipartFormDataContent
        /// </summary>
        /// <param name="data"></param>
        /// <returns>MultipartFormDataContent</returns>
        public static HttpContent ToMultipartFormDataContent(this object data)
        {
            var json = JsonConvert.SerializeObject(data, Formatting.None, new IsoDateTimeConverter());
            var body = new StringContent(json, Encoding.UTF8, "application/json");
            var multipartFormDataContent = new MultipartFormDataContent();
            multipartFormDataContent.Add(body);
            return multipartFormDataContent;
        }

        /// <summary>
        /// Object轉換為FormUrlEncodedContent
        /// </summary>
        /// <param name="data">請求參數</param>
        /// <returns>FormUrlEncodedContent</returns>
        public static HttpContent ToFormUrlEncodedContent(this object data)
        {
            var param = new List<KeyValuePair<string, string>>();
            var values = JObject.FromObject(data);
            foreach (var item in values)
            {
                param.Add(new KeyValuePair<string, string>(item.Key, item.Value.ToString()));
            }
            HttpContent formUrlEncodedContent = new FormUrlEncodedContent(param);
            return formUrlEncodedContent;
        }


        /// <summary>
        /// Object轉換為ByteArrayContent
        /// </summary>
        /// <param name="data">請求參數</param>
        /// <returns>FormUrlEncodedContent</returns>
        public static HttpContent ToByteArrayContent(this object data)
        {
            var json = JsonConvert.SerializeObject(data, Formatting.None, new IsoDateTimeConverter());
            byte[] bytes = Encoding.UTF8.GetBytes(json);
            HttpContent byteArrayContent = new ByteArrayContent(bytes);
            return byteArrayContent;
        }

        /// <summary>
        /// Url編碼
        /// </summary>
        /// <param name="content">內容</param>
        /// <param name="encode">編碼類型</param>
        /// <returns></returns>
        private static string Encode(string content, Encoding encode = null)
        {
            if (encode == null) return content;

            return System.Web.HttpUtility.UrlEncode(content, Encoding.UTF8);

        }


        /// <summary>
        /// Url解碼
        /// </summary>
        /// <param name="content">內容</param>
        /// <param name="encode">編碼類型</param>
        /// <returns></returns>
        private static string Decode(string content, Encoding encode = null)
        {
            if (encode == null) return content;

            return System.Web.HttpUtility.UrlDecode(content, Encoding.UTF8);

        }

        /// <summary>
        /// 將鍵值對參數集合拼接為Url字符串
        /// </summary>
        /// <param name="paramArray">鍵值對集合</param>
        /// <param name="encode">轉碼類型</param>
        /// <returns></returns>
        private static string BuildParam(List<KeyValuePair<string, string>> paramArray, Encoding encode = null)
        {
            string url = "";

            if (encode == null) encode = Encoding.UTF8;

            if (paramArray != null && paramArray.Count > 0)
            {
                var parms = "";
                foreach (var item in paramArray)
                {
                    parms += string.Format("{0}={1}&", Encode(item.Key, encode), Encode(item.Value, encode));
                }
                if (parms != "")
                {
                    parms = parms.TrimEnd('&');
                }
                url += parms;

            }
            return url;
        }
    }
}
View Code

 時間倉促,沒能說的太詳細,有時間再做補充。如本文中的有錯誤示范,歡迎指正

源碼地址:https://github.com/lwc1st/AspNetCore.UploadDemo.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM