1 using System;
2 using System.Collections.Generic;
3 using System.Net.Http.Formatting;
4 using System.Web.Http;
5
6 namespace MvcTest
7 {
8 public static class WebApiConfig
9 {
10 public static void Register(HttpConfiguration config)
11 {
12 //定义路由以支持action
13 //实际开发建议使用此方式
14 config.Routes.MapHttpRoute(
15 name: "ActionApi",
16 routeTemplate: "api3/{controller}/{action}/{key}",
17 defaults: new { key = RouteParameter.Optional }
18 );
19
20
21 //自定义路由,指定默认参数为key
22 //http://localhost:21931/api2/myapi
23 config.Routes.MapHttpRoute(
24 name: "MyApi",
25 routeTemplate: "api2/{controller}/{key}",
26 defaults: new { key = RouteParameter.Optional }
27 );
28
29 config.Routes.MapHttpRoute(
30 name: "DefaultApi",
31 routeTemplate: "api/{controller}/{id}",
32 defaults: new { id = RouteParameter.Optional }
33 );
34 //请求时上送format指定响应的格式
35 //demo:http://localhost:21931/api/myapi?format=json
36 //如果不指定会以浏览器上送的accept来决定,因此在chrome下会返回xml,在ie下会返回json
37 config.Formatters.JsonFormatter.AddQueryStringMapping("format", "json", "application/json");
38 config.Formatters.XmlFormatter.AddQueryStringMapping("format", "xml", "application/xml");
39 }
40 }
41 }
1 using System;
2 using System.Collections.Generic;
3 using System.Net;
4 using System.Net.Http;
5 using System.Web;
6 using System.Web.Http;
7
8 namespace MvcTest.Controllers
9 {
10 public class MyApiController : ApiController
11 {
12 //默认参数为id,务必与路由里的一致,否则会出现404的错误
13 // GET api/myapi
14 public IEnumerable<string> Get()
15 {
16 return new string[] { "value1", "value2" };
17 }
18
19 //返回一个对象
20 //api/myapi/111?format=json返回为json
21 //api/myapi/111?format=xml返回为xml
22 //实现原理参见WebApiConfig配置
23 public User Get(int id)
24 {
25 return new User { Name = "AA", Age = id };
26 }
27
28 //请求方式/api/myapi/?name=wjf&count=111
29 public List<User> Get(string name, int count)
30 {
31 var list = new List<User>();
32 for (int i = 0; i < count; i++)
33 {
34 list.Add(new User { Name = name, Age = count * 2 });
35 }
36 return list;
37 }
38
39 //感受一下webapi的重载
40 public String Post()
41 {
42 return "aa";
43 }
44
45 //感受一下webapi的重载
46 public string Post(string id)
47 {
48 return "post接收到数据:" + id;
49 }
50
51
52 //感受一下webapi的重载
53 //此方法不能与post()共存,这样会导致不知道怎么映射要解决此问题可以通过自定义方法实现
54 //public string Post(User u)
55 //{
56 // if (u == null)
57 // return "无数据";
58 // return "post接收到数据:" + u.ToString();
59 //}
60
61
62 //WEBAPI中的Request是HttpRequestMessage类型,
63 //当参数的名称与路由的名称不一致时,要接收只能通过HttpContext.Current.Request[key]
64 // POST api/myapi
65 //public string Post([FromBody]string value)
66 //{
67 // var a = HttpContext.Current.Request["value"];
68 // if (!string.IsNullOrWhiteSpace(a))
69 // return a;
70 // return "post" + value;
71 //}
72
73
74 //参数默认是FormUri
75 // PUT api/myapi/5
76 public string Put([FromBody]string id)
77 {
78 return "put" + id;
79 }
80
81 // DELETE api/myapi/5
82 public string Delete(string id)
83 {
84 return "Delete" + id;
85 }
86
87 //方法不够时可以自己定义方法,一般不推荐此方法
88 [AcceptVerbs("MY", "HEAD")]
89 public string My([FromBody]string id)
90 {
91 return "My" + id;
92 }
93
94 //自定义方法
95 //注意参数是key哦
96 //查看路由发指定默认参数是key
97 [AcceptVerbs("MYROUTE", "HEAD")]
98 public string MyRoute([FromBody]string key)
99 {
100 return "MYROUTE" + key;
101 }
102
103
104 //调用此方法通过http://localhost:21931/api3/myapi/GetAll,需要先配置好路由
105 //此方法与post()共存时会有问题,路由不知道如何映射
106 //public string MyAll()
107 //{
108 // return "aaaaaaaaaaaaaaaaaaaaa";
109 //}
110
111 }
112
113 public class User
114 {
115 public String Name { get; set; }
116 public int Age { get; set; }
117 public override string ToString()
118 {
119 return string.Format("name:{0},age:{1}", Name, Age);
120 }
121 }
122 }
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title></title>
5 <script src="js/jquery.js" type="text/javascript"></script>
6 <script type="text/javascript">
7 $(function () {
8 $("#btn").click(function () {
9 // //get请求
10 // $.ajax({
11 // type: 'GET',
12 // url: 'api/myapi/123',
13 // success: function (data) {
14 // jalert(data);
15 // },
16 // error: function (xmlHttpRequest, textStatus, errorThrown) {
17 // jalert(11);
18 // }
19 // });
20
21 //调用无参数的post请求
22 // $.ajax({
23 // type: 'POST',
24 // url: 'api/myapi',
25 // success: function (data) {
26 // jalert(data);
27 // },
28 // error: function (xmlHttpRequest, textStatus, errorThrown) {
29 // jalert("调用失败");
30 // }
31 // });
32
33 // $.ajax({
34 // type: 'POST',
35 // url: 'api/myapi',
36 // data: { Name: 'wjf', Age: 123 },
37 // dataType: 'json',
38 // success: function (data) {
39 // jalert(data);
40 // },
41 // error: function (xmlHttpRequest, textStatus, errorThrown) {
42 // jalert(11);
43 // }
44 // });
45
46 // $.ajax({
47 // type: 'PUT',
48 // url: 'api/myapi',
49 // data: { '': '11111' },
50 // dataType: 'json',
51 // success: function (data) {
52 // jalert(data);
53 // },
54 // error: function (xmlHttpRequest, textStatus, errorThrown) {
55 // jalert("调用失败");
56 // }
57 // });
58
59 // $.ajax({
60 // type: 'Delete',
61 // url: 'api/myapi/11111111',
62 // success: function (data) {
63 // jalert(data);
64 // },
65 // error: function (xmlHttpRequest, textStatus, errorThrown) {
66 // jalert("调用失败");
67 // }
68 // });
69
70 //调用自己定义的方法
71 // $.ajax({
72 // type: 'MY',
73 // url: 'api/myapi/我是URL参数',
74 // success: function (data) {
75 // jalert(data);
76 // },
77 // error: function (xmlHttpRequest, textStatus, errorThrown) {
78 // jalert("调用失败");
79 // }
80 // });
81
82 //调用自己定义的方法
83 // $.ajax({
84 // type: 'MY',
85 // url: 'api/myapi',
86 // data: { '': '我是json传的值' },//如果要传多个值,是不支持这种写法的(formbody只支持一个修饰),需要定义一个对象对接收
87 // dataType: 'json',
88 // success: function (data) {
89 // jalert(data);
90 // },
91 // error: function (xmlHttpRequest, textStatus, errorThrown) {
92 // jalert("调用失败");
93 // }
94 // });
95
96
97 // $.ajax({
98 // type: 'MYROUTE',
99 // url: 'api2/myapi',
100 // data: { '': '我是json传的值' }, //如果要传多个值,是不支持这种写法的(formbody只支持一个修饰),需要定义一个对象对接收
101 // dataType: 'json',
102 // success: function (data) {
103 // jalert(data);
104 // },
105 // error: function (xmlHttpRequest, textStatus, errorThrown) {
106 // jalert("调用失败");
107 // }
108 // });
109
110 });
111 });
112 function jalert(msg) {
113 $("#msg").html(msg);
114 }
115 </script>
116 </head>
117 <body>
118 <input type="button" value="测试" id="btn" />
119 <span id="msg"></span>
120 </body>
121 </html>