webform应用程序asp.net中最好的调用web api c# [英] the best calling web api in webform application asp.net c#

查看:467
本文介绍了webform应用程序asp.net中最好的调用web api c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类似于
的web api

i created a web api like this

和控制器:

 public tbl_Users   Get(int  id)
    {
        DocManagerEntities1 db = new DocManagerEntities1();
        var data = from item in db.tbl_Users
                   where item.U_ID == id
                   select item;
        return data.FirstOrDefault();
    }

现在我想在asp.net中调用这个api c#webform application
最好的方法是什么?
(我不想用Jquery做这件事)
非常感谢

now i want to call this api in asp.net c# webform application whats the best way to do this ? (i dont want do this with Jquery) thanks alot

推荐答案

这是我的Api实现

模型

public class Cars
    {
        public string carName;
        public string carRating;
        public string carYear;
    }

我的api控制器

public class DefaultController : ApiController
    {
        public HttpResponseMessage GetCarses()
        {
            List<Cars> carList = new List<Cars>();
            carList.Add(new Cars
            {
                carName = "a",
                carRating = "b",
                carYear = "c"
            });
            carList.Add(new Cars
            {
                carName = "d",
                carRating = "e",
                carYear = "f"
            });
            return Request.CreateResponse(HttpStatusCode.OK, carList); ;
        } 
    }

以及我对HttpClient的回复

and my response from HttpClient

  String jsonData;
            string url =
                String.Format(
                    @" http://localhost:37266/api/Default/GetCars");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {

                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    jsonData = reader.ReadToEnd();
                }

                //Console.WriteLine(jsonData);
            }
            var cars = new JavaScriptSerializer().Deserialize<List<Cars>>(jsonData);
            var ss = cars;

别忘了添加

 protected void Application_Start()
        {
            //add this line if not 
            GlobalConfiguration.Configure(WebApiConfig.Register);
            ...
        }

这篇关于webform应用程序asp.net中最好的调用web api c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆