环境:

  • vs2019 16.5.1
  • aspnetcore 3.1.1
  • fiddler
  • restsharp 106.10.1

说明:
要测试restsharp的功能,首先需要了解http传参和下载上传文件的原理,请参考:
c#:从http请求报文看http协议中参数传递的几种方式
c#使用Http上传下载文件

.net core/.net 5/.net 6 及以上框架,建议直接使用 HttpClient,参照:《c#:HttpClient使用详解》

一、restsharp介绍

RestSharp是一个轻量的,不依赖任何第三方的组件或者类库的Http的组件。RestSharp具体以下特性:
1、支持.NET 3.5+,Silverlight 4, Windows Phone 7, Mono, MonoTouch, Mono for Android, Compact Framework 3.5,.NET Core等
  2、通过NuGet方便引入到任何项目 ( Install-Package restsharp )
  3、可以自动反序列化XML和JSON
  4、支持自定义的序列化与反序列化
  5、自动检测返回的内容类型
  6、支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作
  7、可以上传多文件
  8、支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授权验证等
  9、支持异步操作
  10、极易上手并应用到任何项目中
以上是RestSharp的主要特点,通用它你可以很容易地用程序来处理一系列的网络请求(GET, POST, PUT, HEAD, OPTIONS, DELETE),并得到返回结果。
restsharp官网:http://restsharp.org/

二、首先准备webapi项目

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace testweb.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class TestController : ControllerBase
    {
        public async Task<IEnumerable<object>> TestGet()
        {
            return new object[] { new { Name = "小明", age = 20 }, new { Name = "小花", age = 18 } };
        }

        public async Task<IEnumerable<object>> TestPost()
        {
            return new object[] { new { Name = "post小明", age = 20 }, new { Name = "post小花", age = 18 } };
        }

        [HttpGet]
        [HttpPost]
        public async Task<string> TestUrlPara([FromQuery]string name, [FromQuery]int? age)
        {
            return $"hello {name},你{age}岁了!";
        }


        [HttpPost]
        public async Task<string> TestPostUrlFormUrlencoded([FromForm]string name, [FromForm]int? age)
        {
            return $"hello {name},你{age}岁了!";
        }

        [HttpPost]
        public async Task<string> TestPostUrlFormData([FromForm]string name, [FromForm]int? age)
        {
            return $"hello {name},你{age}岁了,你上传了{Request.Form.Files.Count}个文件!";
        }

        [HttpPost]
        public string TestBodyJson([FromBody]User user)
        {
            if (user == null) return "user is null.";
            return Newtonsoft.Json.JsonConvert.SerializeObject(user);
        }

        [HttpGet]
        public IActionResult TestDownLoad()
        {
            var filepath = @"C:\Users\AUAS\Pictures\百度下载图片\timg.jpg";
            FileStream fs = new FileStream(filepath, FileMode.Open);
            return File(fs, "application/octet-stream", "test.png");
        }
    }
    public class User
    {
        public string name { get; set; }
        public int? id { get; set; }
    }
}

三、开始测试restsharp发送各种类型http请求和下载文件

3.1 首先nuget包引入restsharp

在这里插入图片描述

3.2 直接看测试代码

using RestSharp;
using System;
using System.IO;

namespace restsharpdemo
{
    class Program
    {
        private static RestClient client = new RestClient("http://localhost:5000/");
        static void Main(string[] args)
        {
            //TestGet();
            //TestPost();
            //TestUrlPara();
            //TestPostUrlFormUrlencoded();
            //TestPostUrlFormData();
            //TestBodyJson();
            //TestDownLoad();
            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }

        /// <summary>
        /// 测试下载文件
        /// </summary>
        private static void TestDownLoad()
        {
            string tempFile = Path.GetTempFileName();
            using (var writer = File.OpenWrite(tempFile))
            {
                var req = new RestRequest("test/TestDownLoad", Method.GET);
                req.ResponseWriter = responseStream =>
                {
                    using (responseStream)
                    {
                        responseStream.CopyTo(writer);
                    }
                };
                var response = client.DownloadData(req);
            }
        }

        /// <summary>
        /// 测试传递application/json类型参数
        /// </summary>
        private static void TestBodyJson()
        {
            var req = new RestRequest("test/TestBodyJson", Method.POST);
            req.AddJsonBody(new { name = "小花", id = 23 });
            var res = client.Execute(req);
            if (res.IsSuccessful)
            {
                Console.WriteLine($"成功:{res.Content}");
            }
            else
            {
                if (res.StatusCode == 0)
                {
                    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
                }
                else
                {
                    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
                }
            }
        }

        /// <summary>
        /// 测试传递post multipart/form-data参数
        /// </summary>
        private static void TestPostUrlFormData()
        {
            var req = new RestRequest("test/TestPostUrlFormData", Method.POST);
            req.AlwaysMultipartFormData = true;
            req.AddParameter("name", "小明");
            req.AddParameter("age", "20");
            req.AddFile("file1", @"C:\Users\AUAS\Pictures\百度下载图片\timg.jpg");
            var res = client.Execute(req);
            if (res.IsSuccessful)
            {
                Console.WriteLine($"成功:{res.Content}");
            }
            else
            {
                if (res.StatusCode == 0)
                {
                    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
                }
                else
                {
                    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
                }
            }
        }

        /// <summary>
        /// 测试传递post application/x-www-form-urlencoded参数
        /// </summary>
        private static void TestPostUrlFormUrlencoded()
        {
            var req = new RestRequest("test/TestPostUrlFormUrlencoded", Method.POST);
            //将参数编码后加到url上
            req.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            req.AddParameter("name", "小明");
            req.AddParameter("age", "20");
            var res = client.Execute(req);
            if (res.IsSuccessful)
            {
                Console.WriteLine($"成功:{res.Content}");
            }
            else
            {
                if (res.StatusCode == 0)
                {
                    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
                }
                else
                {
                    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
                }
            }
        }

        /// <summary>
        /// 测试传递url参数
        /// </summary>
        private static void TestUrlPara()
        {
            var req = new RestRequest("test/TestUrlPara", Method.GET);
            req = new RestRequest("test/TestUrlPara", Method.POST);
            //将参数编码后加到url上
            req.AddParameter("name", "小明");
            req.AddParameter("age", "18");
            var res = client.Get(req);
            if (res.IsSuccessful)
            {
                Console.WriteLine($"成功:{res.Content}");
            }
            else
            {
                if (res.StatusCode == 0)
                {
                    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
                }
                else
                {
                    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
                }
            }
        }

        /// <summary>
        /// 测试简单post
        /// </summary>
        private static void TestPost()
        {
            var req = new RestRequest("test/testpost", Method.POST);
            var res = client.Post(req);
            if (res.IsSuccessful)
            {
                Console.WriteLine($"成功:{res.Content}");
            }
            else
            {
                if (res.StatusCode == 0)
                {
                    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
                }
                else
                {
                    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
                }

            }
        }

        /// <summary>
        /// 测试简单get
        /// </summary>
        private static void TestGet()
        {
            var req = new RestRequest("test/testget", Method.GET);
            var res = client.Get(req);
            if (res.IsSuccessful)
            {
                Console.WriteLine($"成功:{res.Content}");
            }
            else
            {
                if (res.StatusCode == 0)
                {
                    Console.WriteLine($"失败:网络错误:{res.ErrorMessage}");
                }
                else
                {
                    Console.WriteLine($"失败:{(int)res.StatusCode}-{res.StatusDescription}");
                }

            }
        }
    }
}
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐