本篇主要介绍WepApi响应Http method 中的Get方法:
创建空的WebApi解决方案:
在Model文件夹中添加Person类,内容如下:
public class Person { public string ID { get;set;} public string Name { get; set; } public string Sex { get; set; } public string Phone { get; set; } public string Addres { get; set; } }
下面我们在Controller文件夹中创建一个空的WebApi控制器PeopleController,其内容如下:
public class PeopleController : ApiController { Person [] people = new Person[]{ new Person() { ID ="001", Name = "dongdong", Sex ="男", Phone ="123456789", Address ="河南南阳" }, new Person() { ID ="002", Name = "wang", Sex ="女", Phone ="456123789", Address ="河南南阳" }, new Person() { ID ="003", Name = "zhao", Sex ="男", Phone ="123789456", Address ="河南南阳" }, new Person() { ID ="004", Name = "sun", Sex ="女", Phone ="789123456", Address ="河南南阳" }, }; public IEnumerable<Person> Get() { return people; } public IHttpActionResult GetPerson(string id) { var person = people.FirstOrDefault((p) => p.ID == id); if (person == null) { return NotFound(); } return Ok(person); } }
上面的controller中我添加了一个Person的数组用来代替数据,定义了两个以Get开头的函数用来响应Http的Get消息,第一个Get函数返回所有的person数据,第二个GetPerson函数返回特定ID的数据。
在Advenced上测试:
一、
URl=http://localhost:7281/api/People
结果:
[4] 0: { ID: "001" Name: "dongdong" Sex: "男" Phone: "123456789" Address: "河南南阳" }- 1: { ID: "002" Name: "wang" Sex: "女" Phone: "456123789" Address: "河南南阳" }- 2: { ID: "003" Name: "zhao" Sex: "男" Phone: "123789456" Address: "河南南阳" }- 3: { ID: "004" Name: "sun" Sex: "女" Phone: "789123456" Address: "河南南阳" }
二:
URL=http://localhost:7281/api/People/001
结果:
{ ID: "001" Name: "dongdong" Sex: "男" Phone: "123456789" Address: "河南南阳" }
综上:WebApi响应Get方法时控制器的函数可以以Get作为前缀,或者是用C#的Attribute属性来设置路由,如[Route("/getall")]等。
由于Get方法的响应只是读取数据的,所以其参数比较简单可以通过URL来传递,但是当Put,Post方法的响应函数的参数为复杂参数的时候如何传递参数呢?又如何通过Advanced测试呢?
时间: 2024-10-13 01:24:10