注释玩转webapi

 using System;
using System.Collections.Generic;
using System.Net.Http.Formatting;
using System.Web.Http; namespace MvcTest
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//定义路由以支持action
//实际开发建议使用此方式
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api3/{controller}/{action}/{key}",
defaults: new { key = RouteParameter.Optional }
); //自定义路由,指定默认参数为key
//http://localhost:21931/api2/myapi
config.Routes.MapHttpRoute(
name: "MyApi",
routeTemplate: "api2/{controller}/{key}",
defaults: new { key = RouteParameter.Optional }
); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//请求时上送format指定响应的格式
//demo:http://localhost:21931/api/myapi?format=json
//如果不指定会以浏览器上送的accept来决定,因此在chrome下会返回xml,在ie下会返回json
config.Formatters.JsonFormatter.AddQueryStringMapping("format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("format", "xml", "application/xml");
}
}
}
 using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http; namespace MvcTest.Controllers
{
public class MyApiController : ApiController
{
//默认参数为id,务必与路由里的一致,否则会出现404的错误
// GET api/myapi
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
} //返回一个对象
//api/myapi/111?format=json返回为json
//api/myapi/111?format=xml返回为xml
//实现原理参见WebApiConfig配置
public User Get(int id)
{
return new User { Name = "AA", Age = id };
} //请求方式/api/myapi/?name=wjf&count=111
public List<User> Get(string name, int count)
{
var list = new List<User>();
for (int i = ; i < count; i++)
{
list.Add(new User { Name = name, Age = count * });
}
return list;
} //感受一下webapi的重载
public String Post()
{
return "aa";
} //感受一下webapi的重载
public string Post(string id)
{
return "post接收到数据:" + id;
} //感受一下webapi的重载
//此方法不能与post()共存,这样会导致不知道怎么映射要解决此问题可以通过自定义方法实现
//public string Post(User u)
//{
// if (u == null)
// return "无数据";
// return "post接收到数据:" + u.ToString();
//} //WEBAPI中的Request是HttpRequestMessage类型,
//当参数的名称与路由的名称不一致时,要接收只能通过HttpContext.Current.Request[key]
// POST api/myapi
//public string Post([FromBody]string value)
//{
// var a = HttpContext.Current.Request["value"];
// if (!string.IsNullOrWhiteSpace(a))
// return a;
// return "post" + value;
//} //参数默认是FormUri
// PUT api/myapi/5
public string Put([FromBody]string id)
{
return "put" + id;
} // DELETE api/myapi/5
public string Delete(string id)
{
return "Delete" + id;
} //方法不够时可以自己定义方法,一般不推荐此方法
[AcceptVerbs("MY", "HEAD")]
public string My([FromBody]string id)
{
return "My" + id;
} //自定义方法
//注意参数是key哦
//查看路由发指定默认参数是key
[AcceptVerbs("MYROUTE", "HEAD")]
public string MyRoute([FromBody]string key)
{
return "MYROUTE" + key;
} //调用此方法通过http://localhost:21931/api3/myapi/GetAll,需要先配置好路由
//此方法与post()共存时会有问题,路由不知道如何映射
//public string MyAll()
//{
// return "aaaaaaaaaaaaaaaaaaaaa";
//} } public class User
{
public String Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return string.Format("name:{0},age:{1}", Name, Age);
}
}
}
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
// //get请求
// $.ajax({
// type: 'GET',
// url: 'api/myapi/123',
// success: function (data) {
// jalert(data);
// },
// error: function (xmlHttpRequest, textStatus, errorThrown) {
// jalert(11);
// }
// }); //调用无参数的post请求
// $.ajax({
// type: 'POST',
// url: 'api/myapi',
// success: function (data) {
// jalert(data);
// },
// error: function (xmlHttpRequest, textStatus, errorThrown) {
// jalert("调用失败");
// }
// }); // $.ajax({
// type: 'POST',
// url: 'api/myapi',
// data: { Name: 'wjf', Age: 123 },
// dataType: 'json',
// success: function (data) {
// jalert(data);
// },
// error: function (xmlHttpRequest, textStatus, errorThrown) {
// jalert(11);
// }
// }); // $.ajax({
// type: 'PUT',
// url: 'api/myapi',
// data: { '': '11111' },
// dataType: 'json',
// success: function (data) {
// jalert(data);
// },
// error: function (xmlHttpRequest, textStatus, errorThrown) {
// jalert("调用失败");
// }
// }); // $.ajax({
// type: 'Delete',
// url: 'api/myapi/11111111',
// success: function (data) {
// jalert(data);
// },
// error: function (xmlHttpRequest, textStatus, errorThrown) {
// jalert("调用失败");
// }
// }); //调用自己定义的方法
// $.ajax({
// type: 'MY',
// url: 'api/myapi/我是URL参数',
// success: function (data) {
// jalert(data);
// },
// error: function (xmlHttpRequest, textStatus, errorThrown) {
// jalert("调用失败");
// }
// }); //调用自己定义的方法
// $.ajax({
// type: 'MY',
// url: 'api/myapi',
// data: { '': '我是json传的值' },//如果要传多个值,是不支持这种写法的(formbody只支持一个修饰),需要定义一个对象对接收
// dataType: 'json',
// success: function (data) {
// jalert(data);
// },
// error: function (xmlHttpRequest, textStatus, errorThrown) {
// jalert("调用失败");
// }
// }); // $.ajax({
// type: 'MYROUTE',
// url: 'api2/myapi',
// data: { '': '我是json传的值' }, //如果要传多个值,是不支持这种写法的(formbody只支持一个修饰),需要定义一个对象对接收
// dataType: 'json',
// success: function (data) {
// jalert(data);
// },
// error: function (xmlHttpRequest, textStatus, errorThrown) {
// jalert("调用失败");
// }
// }); });
});
function jalert(msg) {
$("#msg").html(msg);
}
</script>
</head>
<body>
<input type="button" value="测试" id="btn" />
<span id="msg"></span>
</body>
</html>
上一篇:laravel5.5解决小程序登陆态的问题


下一篇:20145324王嘉澜 《网络对抗技术》 MAL_逆向与Bof基础