h5调用第三方api时候经常遇到不允许跨域的问题,用webapi实现一个代理http接口,方便进行跨域请求。
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using YFAPICommon.Models; namespace YFAPICommon.Controllers { public class HttpInput { public string url { set; get; } public Dictionary<string,object> param { set; get; } } public class HttpProxyController : ApiController { public object doPost(HttpInput input) { if (string.IsNullOrWhiteSpace(input.url)) return ReturnNode.ReturnError("url不能为空"); if (input.param == null) input.param = new Dictionary<string, object>(); string result = Post(input.url,input.param); if (result != null) { try { JObject obj = JsonConvert.DeserializeObject<JObject>(result); return obj; } catch (Exception ex) { } } return result; } public object doGet(HttpInput input) { if (string.IsNullOrWhiteSpace(input.url)) return ReturnNode.ReturnError("url不能为空"); if (input.param == null) input.param = new Dictionary<string, object>(); string result = Get(input.url); if (result != null) { try { JObject obj = JsonConvert.DeserializeObject<JObject>(result); return obj; } catch (Exception ex) { } } return result; } private static string Post(string url, Dictionary<string, object> param) { using (HttpClient client = new HttpClient()) { //请求超时 //client.Timeout = new TimeSpan(5000); var httpContent = new StringContent(JsonConvert.SerializeObject(param)); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = client.PostAsync(url, httpContent).Result; var responseValue = response.Content.ReadAsStringAsync().Result; if (response.StatusCode == System.Net.HttpStatusCode.OK) { return responseValue; } return null; } } private static string Get(string url) { var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return responseString; } return null; } } }