【问题标题】:the best calling web api in webform application asp.net c#webform应用程序asp.net c#中最好的调用web api
【发布时间】:2016-10-14 16:34:13
【问题描述】:

我创建了一个这样的 web api

和控制器:

 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 c# webform 应用程序中调用这个 api 最好的方法是什么? (我不想用 Jquery 做这个) 非常感谢

【问题讨论】:

  • 那么如何调用api呢?
  • @syedmhamudulhasanakash 调用 http 客户端

标签: c# asp.net api http


【解决方案1】:

这是我的 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 的回应

  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);
            ...
        }

【讨论】:

    猜你喜欢
    • 2020-10-13
    • 1970-01-01
    • 2017-04-29
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多