WebApi实现代理Http请求

偏执的太偏执、 2023-10-09 12:57 60阅读 0赞

h5调用第三方api时候经常遇到不允许跨域的问题,用webapi实现一个代理http接口,方便进行跨域请求。

  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using System.Web.Http;
  11. using YFAPICommon.Models;
  12. namespace YFAPICommon.Controllers
  13. {
  14. public class HttpInput
  15. {
  16. public string url { set; get; }
  17. public Dictionary<string,object> param { set; get; }
  18. }
  19. public class HttpProxyController : ApiController
  20. {
  21. public object doPost(HttpInput input)
  22. {
  23. if (string.IsNullOrWhiteSpace(input.url))
  24. return ReturnNode.ReturnError("url不能为空");
  25. if (input.param == null)
  26. input.param = new Dictionary<string, object>();
  27. string result = Post(input.url,input.param);
  28. if (result != null)
  29. {
  30. try
  31. {
  32. JObject obj = JsonConvert.DeserializeObject<JObject>(result);
  33. return obj;
  34. }
  35. catch (Exception ex)
  36. {
  37. }
  38. }
  39. return result;
  40. }
  41. public object doGet(HttpInput input)
  42. {
  43. if (string.IsNullOrWhiteSpace(input.url))
  44. return ReturnNode.ReturnError("url不能为空");
  45. if (input.param == null)
  46. input.param = new Dictionary<string, object>();
  47. string result = Get(input.url);
  48. if (result != null)
  49. {
  50. try
  51. {
  52. JObject obj = JsonConvert.DeserializeObject<JObject>(result);
  53. return obj;
  54. }
  55. catch (Exception ex)
  56. {
  57. }
  58. }
  59. return result;
  60. }
  61. private static string Post(string url, Dictionary<string, object> param)
  62. {
  63. using (HttpClient client = new HttpClient())
  64. {
  65. //请求超时
  66. //client.Timeout = new TimeSpan(5000);
  67. var httpContent = new StringContent(JsonConvert.SerializeObject(param));
  68. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  69. var response = client.PostAsync(url, httpContent).Result;
  70. var responseValue = response.Content.ReadAsStringAsync().Result;
  71. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  72. {
  73. return responseValue;
  74. }
  75. return null;
  76. }
  77. }
  78. private static string Get(string url)
  79. {
  80. var request = (HttpWebRequest)WebRequest.Create(url);
  81. var response = (HttpWebResponse)request.GetResponse();
  82. var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  83. if (response.StatusCode == System.Net.HttpStatusCode.OK)
  84. {
  85. return responseString;
  86. }
  87. return null;
  88. }
  89. }
  90. }

发表评论

表情:
评论列表 (有 0 条评论,60人围观)

还没有评论,来说两句吧...

相关阅读