Web应用调用.Net Core API
一、新建Web Application应用:
选择Web Application
新建好之后页面如下:
二、新建Model。新建Model文件夹并建立apiModel.cs。
三、添加reference。
将Newtonsoft.Json添加到项目中。因为需要将json数据转换成对象,因此需要添加reference。
四、建立呼叫API的服务。
public class callapi_service { public static TResult<T> getApiModels<T>(string strMethod, int id) { string result = string.Empty; TResult<T> models; string apiUrl = ""; if (strMethod=="GET") //apiUrl += getUrlQueryString(id); apiUrl = "http://localhost:19357/api/values/"+id; try { HttpWebRequest request = HttpWebRequest.Create(apiUrl) as HttpWebRequest; request.Method = strMethod; //request.ContentType = httpContentType; //request.Timeout = timeout; //request.Headers.Add(keyHeaderAuthorization, getApiToken()); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { string strHttpStatus = response.StatusCode.ToString(); using (StreamReader sr = new StreamReader(response.GetResponseStream())) { result = sr.ReadToEnd(); } } models = JsonConvert.DeserializeObject<TResult<T>>(result); } catch (WebException ex) { models = default(TResult<T>); models.rc = 99; models.msg = ex.Message; } catch (Exception ex) { models = default(TResult<T>); models.rc = 99; models.msg = ex.Message; } return models; } #region TResult public class TResult { /// <summary> /// result code /// </summary> public int rc { get; set; } /// <summary> /// error message /// </summary> public string msg { get; set; } } public class TResult<T> : TResult { /// <summary> /// result code /// </summary> public int rc { get; set; } /// <summary> /// error message /// </summary> public string msg { get; set; } public T data { get; set; } } #endregion }
五、修改页面Default.aspx。
六、处理后台代码类Default.aspx.cs.
protected void Page_Load(object sender, EventArgs e) { var result=callapi_service.getApiModels<List<apiModel>>("GET",1); gvApprovalList.DataSource = result.data; gvApprovalList.DataBind(); }
七、成功