【RestSharp】常用的几个请求方式
前言
经常用到,做个记录
代码
(1)Get-Request.Query取值
var url = "http://localhost:5000/api/RestSharp/TestGet"; var param = new Dictionary<string, string> { { "User", "123456789@qq.com" }, { "Pwd", "123$%^qwe..." }, }; var client = new RestClient(url); RestRequest request = new() { Method = Method.Get }; foreach (var item in param) { request.AddQueryParameter(item.Key, item.Value); } RestResponse response = await client.ExecuteAsync(request); Console.WriteLine(response.Content);
(2)Get-FromQuery取值
var url = "http://localhost:5000/api/RestSharp/TestGetQuery"; var param = new Dictionary<string, string> { { "User", "123456789@qq.com" }, { "Pwd", "123$%^qwe..." }, }; var client = new RestClient(url); RestRequest request = new() { Method = Method.Get }; foreach (var item in param) { request.AddQueryParameter(item.Key, item.Value); } RestResponse response = await client.ExecuteAsync(request); Console.WriteLine(response.Content);
(3)Post-Body-Json方式
var url = "http://localhost:5000/api/RestSharp/TestPostBodyJson"; var headers = new Dictionary<string, string> { { "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" }, }; var param = new Dictionary<string, string> { { "User", "123456789@qq.com" }, { "Pwd", "123$%^qwe..." }, }; var client = new RestClient(url); RestRequest request = new() { Method = Method.Post }; request.AddOrUpdateHeaders(headers); request.AddHeader("Content-Type", "application/json"); var body = JsonSerializer.Serialize(param); request.AddStringBody(body, DataFormat.Json); RestResponse response = await client.ExecuteAsync(request); Console.WriteLine(response.Content);
(4)Post-Body-Text方式
var url = "http://localhost:5000/api/RestSharp/TestPostBodyText"; var param = new Dictionary<string, string> { { "User", "123456789@qq.com" }, { "Pwd", "123$%^qwe..." }, }; var client = new RestClient(url); RestRequest request = new() { Method = Method.Post }; request.AddHeader("Content-Type", "text/plain"); var body = string.Join("&", param.Select(p => WebUtility.UrlEncode(p.Key) + "=" + WebUtility.UrlEncode(p.Value))); request.AddParameter("text/plain", body, ParameterType.RequestBody); RestResponse response = await client.ExecuteAsync(request); Console.WriteLine(response.Content);
(5)Post-Form
var url = "http://localhost:5000/api/RestSharp/TestPostForm"; var headers = new Dictionary<string, string> { { "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" }, }; var param = new Dictionary<string, string> { { "User", "123456789@qq.com" }, { "Pwd", "123$%^qwe..." }, }; var client = new RestClient(url); RestRequest request = new() { Method = Method.Post }; request.AddOrUpdateHeaders(headers); foreach (var item in param) request.AddOrUpdateParameter(item.Key, item.Value); RestResponse response = await client.ExecuteAsync(request); Console.WriteLine(response.Content);
(6)Post-Form-禁止重定向
var url = "http://localhost:5000/api/RestSharp/Tokens"; var headers = new Dictionary<string, string> { { "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" }, { "X-Forwarded-For", "123.321.123.321" }, }; var param = new Dictionary<string, string> { { "User", "123456789@qq.com" }, { "Pwd", "123$%^qwe..." }, }; var client = new RestClient(url, options => { options.FollowRedirects = false; }); RestRequest request = new() { Method = Method.Post }; request.AddOrUpdateHeaders(headers); foreach (var item in param) request.AddOrUpdateParameter(item.Key, item.Value); RestResponse response = await client.ExecuteAsync(request); if (((int)response.StatusCode) != 303) Console.WriteLine((int)response.StatusCode); string location = response.Headers?.Where(x => x.Name == "Location").FirstOrDefault()?.Value ?? ""; Console.WriteLine(location);
后端响应代码
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.IO; using System.Threading.Tasks; using Tool.Utility.Standard.Models; namespace WebTaskManageApi.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class RestSharpController : Controller { private readonly IHttpContextAccessor _httpContextAccessor; public RestSharpController(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } [HttpGet] public async Task<ResponseDto<string>> TestGet() { var query = _httpContextAccessor.HttpContext.Request.Query; RestSharpDto dto = new RestSharpDto(); foreach (var item in query) { if (item.Key == "User") dto.User = item.Value; else if (item.Key == "Pwd") dto.User = item.Value; } return new ResponseDto<string> { Code = 200, Data = dto.User, }; } [HttpGet] public async Task<ResponseDto<string>> TestGetQuery([FromQuery] RestSharpDto dto) { return new ResponseDto<string> { Code = 200, Data = dto.User, }; } [HttpPost] public async Task<ResponseDto<string>> TestPostBodyJson([FromBody] RestSharpDto dto) { var headers = _httpContextAccessor.HttpContext.Request.Headers; string userAgentKey = "User-Agent"; string userAgent = string.Empty; if (headers.ContainsKey(userAgentKey)) { userAgent = headers[userAgentKey]; } return new ResponseDto<string> { Code = 200, Data = dto.User, Message = userAgent, }; } [HttpPost] public async Task<ResponseDto<string>> TestPostBodyText() { string body = string.Empty; if (Request.ContentType == "text/plain") { using StreamReader reader = new StreamReader(Request.Body); body = await reader.ReadToEndAsync(); } var headers = _httpContextAccessor.HttpContext.Request.Headers; string userAgentKey = "User-Agent"; string userAgent = string.Empty; if (headers.ContainsKey(userAgentKey)) { userAgent = headers[userAgentKey]; } return new ResponseDto<string> { Code = 200, Data = body, Message = userAgent, }; } [HttpPost] public async Task<ResponseDto<string>> TestPostForm([FromForm] RestSharpDto dto) { var headers = _httpContextAccessor.HttpContext.Request.Headers; string userAgentKey = "User-Agent"; string userAgent = string.Empty; if (headers.ContainsKey(userAgentKey)) { userAgent = headers[userAgentKey]; } return new ResponseDto<string> { Code = 200, Data = dto.User, Message = userAgent, }; } } public class RestSharpDto { public string User { get; set; } public string Pwd { get; set; } } }
测试结果
{"code":200,"message":null,"data":"123$%^qwe..."} {"code":200,"message":null,"data":"123456789@qq.com"} {"code":200,"message":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 RestSharp/112.1.0.0","data":"123456789@qq.com"} {"code":200,"message":"RestSharp/112.1.0.0","data":"User=123456789%40qq.com&Pwd=123%24%25%5Eqwe..."} {"code":200,"message":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 RestSharp/112.1.0.0","data":"123456789@qq.com"}