Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

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

i created a web api like this enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...