c# 后端请求另一个后端
后端请求另一个后端,类似以前端请求后端。这里用到 HttpClient 类。
var _httpClient = new HttpClient();
var tokenHeader = HttpContext.Request.Headers["Authorization"].ToString(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", tokenHeader); var parms = new { TTDH_DingS = gxb.TTDH_DingS, ShiGuDM = gxb.ShiGuDM, CPH = gxb.CPH, COLOR = gxb.Color }; string json = JsonConvert.SerializeObject(parms); var content = new StringContent(json, Encoding.UTF8, "application/json"); var dingsundata = (await _httpClient.GetAsync("http://localhost:8081/api/DingSun/ShowDSCLBaseJBInfo?TTDH_DingS=" + gxb.TTDH_DingS + "&ShiGuDM=" + gxb.ShiGuDM + "&CPH=" + gxb.CPH + "&COLOR=" + gxb.Color)); //var dingsundata = (await _httpClient.PostAsync("http://localhost:8081/api/DingSun/ShowDSCLBaseJBInfo", content)); var responseValue = await dingsundata.Content.ReadAsStringAsync(); if (dingsundata.StatusCode == System.Net.HttpStatusCode.OK) { var resftp = JsonConvert.DeserializeObject(responseValue); MessageModel<DingSunIndexPrice> obj = JsonConvert.DeserializeObject<MessageModel<DingSunIndexPrice>>(responseValue); if (obj.success) { DingSunIndexPrice dinsunPrice = obj.response; } }
还有文件流的方式
using (MemoryStream memoryStream = new MemoryStream(file)) { //file 是byte[] 流文件 var _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", token); var content = new MultipartFormDataContent(); content.Add(new StreamContent(memoryStream, (int)memoryStream.Length), "file", fileName); var dingsundata = (await _httpClient.PostAsync(url, content)); var responseValue = await dingsundata.Content.ReadAsStringAsync(); if (dingsundata.StatusCode == System.Net.HttpStatusCode.OK) { var resftp = JsonConvert.DeserializeObject(responseValue); MessageModel<List<string>> obj = JsonConvert.DeserializeObject<MessageModel<List<string>>>(responseValue); if (obj.success) { return obj.response[0]; } else { return ""; } }
但是 同一个项目中,自己模拟前端请求是不能成功的,总会被拦截了。