C# 调接口
作者:互联网
上一个项目,需要mvc管理后台调接口项目,以便后期的重构扩展,调研后发现后台用的ajax请求,直接调接口可能会有跨域问题,最终在c#代码中实现了这个需求。
1,Ajax请求后台 将接口所需参数传入
2,模拟请求接口并返回json格式数据
3,将json数据反序列化
整体代码如下:
public ActionResult Test(int id, int type) { var domain = CommonConst.ApiDomain; var fixedString = CommonConst.FixedString; var thisTimeValue = ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds).ToString(); var tempList = new List<string>() { fixedString.ToLower(), thisTimeValue.ToLower(), "GetTestData".ToLower() }; tempList.Sort(); var valueSign = Encrypt.MD5(string.Join("", tempList)); valueSign = valueSign.ToLower().Replace("-", ""); string serviceAddress = domain + "/api/exam/GetTestData?id=" + id + "&type=" + type; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress); request.Method = CommonConst.RequestMethod; request.ContentType = CommonConst.ContentType; request.Headers.Add("SignsValue", valueSign); request.Headers.Add("TimeStamp", thisTimeValue.ToLower()); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); string retString = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); var result = JsonConvert.DeserializeObject<TestViewModel.RootObject>(retString);
其中 1. SignsValue 和 TimeStamp 等请求头信息需要通过接口的具体规则来实现
2.在反序列化的时候需要定义类来将接受到的json格式数据转化为model 即:JsonConvert.DeserializeObject<TestViewModel.RootObject>(retString);
定义 RootObject 类:
public class RootObject { public string Msg { get; set; } public string Message { get; set; } public string ResultCode { get; set; } public Info Info { get; set; } }
Info 中的数据接口要跟接口的数据结构一致。
GetTestData
标签:string,C#,request,接口,var,public,ToLower 来源: https://www.cnblogs.com/teng-0802/p/10337358.html