简体   繁体   中英

the best calling web api in webform application asp.net c#

i created a web api like this 在此处输入图片说明

and the controller :

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

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

Here is my Api implementation

Models

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

my api controller

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

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;

Dont forget to add

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM