通过jQuery和C#分别实现对.NET Core Web Api的访问以及文件上传

2021-04-08 12:24

阅读:513

标签:rms   head   empty   task   实例   space   gif   OLE   memory   

准备工作:

   建立.NET Core Web Api项目

   新建一个用于Api请求的UserInfo类

    public class UserInfo
    {
        public string name { get; set; }
        public int age { get; set; }
        public bool sex { get; set; }
    }

  2、建立.NET Core Web项目

 

一、使用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:57954/API/Default/data",
            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:57954/API/Default/data",
            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

 "file" multiple id="file" />

JS获取文件对象

        var file = document.getElementById("file");
        var files = file.files;
        var formData = new FormData();
        for (var i = 0; i ) {
            formData.append(files[i].name, files[i]);
        }
     formData.append("name", "刘大大");//可追加参数

AJAX请求

        $.ajax({
            url: "http://localhost:57954/API/Default/data",
            type: "POST",
            async: true,
            dataType: "json",
            data: formData,
            contentType: false, 
            processData: false,
            success: function (data) {
                console.log("data:");
                console.log(data);
            }
        });

后台接受

追加的name参数

技术分享图片

传输的文件

技术分享图片

二、使用C#后台访问

(一)、Get访问

 

var url = "http://localhost:57954/API/Default/values";

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

 

(三)、上传文件

技术分享图片技术分享图片
        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);
                }
            }
            string jsonString;
            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 Json("OK");
        }
View Code

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
    {
        /// 
        /// 通过WebRequest发起Get请求
        /// 
        /// 请求地址
        /// JSON字符串
        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;
        }

        /// 
        /// 通过WebRequest发起Post请求
        /// 
        /// 请求地址
        /// 请求参数
        /// JSON字符串
        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;
        }


        /// 
        /// 通过HttpClient发起Get请求
        /// 
        /// 请求地址
        /// JSON字符串
        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;
        }

        /// 
        /// 通过HttpClient发起Post请求
        /// 
        /// 请求地址
        /// 请求参数
        /// JSON字符串
        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;
        }

        /// 
        /// 通过数据来自HttpContent的HttpClient发起Post请求
        /// 
        /// 请求地址
        /// 请求参数
        /// JSON字符串
        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;
        }

        /// 
        /// Object转换为StreamContent
        /// 
        /// 请求参数
        /// StreamContent
        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;
        }

        /// 
        /// Object转换为StringContent
        /// 
        /// 请求参数
        /// StringContent
        public static HttpContent ToStringContent(this object data)
        {
            HttpContent stringContent = new StringContent(JsonConvert.SerializeObject(data));
            return stringContent;
        }

        /// 
        /// Object转换为MultipartFormDataContent
        /// 
        /// 
        /// MultipartFormDataContent
        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;
        }

        /// 
        /// Object转换为FormUrlEncodedContent
        /// 
        /// 请求参数
        /// FormUrlEncodedContent
        public static HttpContent ToFormUrlEncodedContent(this object data)
        {
            var param = new List>();
            var values = JObject.FromObject(data);
            foreach (var item in values)
            {
                param.Add(new KeyValuePair(item.Key, item.Value.ToString()));
            }
            HttpContent formUrlEncodedContent = new FormUrlEncodedContent(param);
            return formUrlEncodedContent;
        }


        /// 
        /// Object转换为ByteArrayContent
        /// 
        /// 请求参数
        /// FormUrlEncodedContent
        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;
        }

        /// 
        /// Url编码
        /// 
        /// 内容
        /// 编码类型
        /// 
        private static string Encode(string content, Encoding encode = null)
        {
            if (encode == null) return content;

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

        }


        /// 
        /// Url解码
        /// 
        /// 内容
        /// 编码类型
        /// 
        private static string Decode(string content, Encoding encode = null)
        {
            if (encode == null) return content;

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

        }

        /// 
        /// 将键值对参数集合拼接为Url字符串
        /// 
        /// 键值对集合
        /// 转码类型
        /// 
        private static string BuildParam(List> 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

 时间仓促,没能说的太详细,有时间再做补充。如本文中的有错误示范,欢迎指正

通过jQuery和C#分别实现对.NET Core Web Api的访问以及文件上传

标签:rms   head   empty   task   实例   space   gif   OLE   memory   

原文地址:https://www.cnblogs.com/lwc1st/p/9089144.html


评论


亲,登录后才可以留言!