1、路由方法
//Web API框架下默认路由格式
routeTemplate: "api/{controller}/{id}"
其中{controller}是该框架下的默认占位符;而{id}是我们自己设置的占位符,用于传递参数。但不与controller方法中形参名相对应。
假设我们请求的url为 http://localhost:xxxxx/api/products/1,默认为get请求。对于框架来说,相当于将products传递给了{controller},框架寻找名称对应的controller;后面的参数1说明只有一个参数,框架根据路由设置,在该controller下寻找合适的方法,返回数据。
如何寻找合适的方法?目前个人总结以下两种情况下url的写法。
2、实验过程
model类:
public class Product
{
public int Id { get; set; }
public string Name{ get; set; }
public string Category { get; set; }
public decimal Price{ get; set; }
}
StudentsController类
public class StudentsController : ApiController
{
Product[] products = new Product[]
{
new Product{ Id = 1,Name = "Tomato Soup", Category="Groceries",Price=1},
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IHttpActionResult GetStudentById(int id,int param)
//第二种参数格式 :int param = 1,下文阐述区别
{
if (param == 0)
return Ok("有param参数");
var student = products.FirstOrDefault(p => p.Id == id);
if(student == null)
{
return NotFound();
}
return Ok(student);
}
}
定义了一个静态数据,该API可返回对静态数据的查询结果。
该Controller有一个Get方法GetStudentById,其中id参数为想要查询的id;param用于测试路由格式,如果param为0,返回一个提示信息。
WebApiConfig.cs文件配置
1.第一种路由格式
public static void Register(HttpConfiguration config)
{
// Web API 路由
config.Routes.MapHttpRoute(
name: "StudentsApi",
routeTemplate: "api/{controller}/root/{id}/{param}",
defaults: new { param = 1 }
);
}
}
该情况下,param参数设置为默认值1。此时api请求可以为以下三种情况:
1)api/students/root/1 id为1,param为默认值1;
2)api/students/root/1/0 id为1,param为传递值0;
2.第二种路由格式
与第一种不同的是,Controller中GetStudentById方法参数形式发生改变,路由设置中defaults项发生改变。
GetStudentById方法改变如下:
//注意这里param参数设置为默认值。
public IHttpActionResult GetStudentById(int id,int param = 1)
{
if (param == 0)
return Ok("有param参数");
var student = products.FirstOrDefault(p => p.Id == id);
if(student == null)
{
return NotFound();
}
return Ok(student);
}
路由defaults设置发生改变:
public static void Register(HttpConfiguration config)
{
// Web API 路由
config.Routes.MapHttpRoute(
name: "StudentsApi",
routeTemplate: "api/{controller}/root/{id}/{param}",
defaults: new { param = RouteParamter.Optional }
);
}
}
此时访问API,除了第一种情况下的两种url请求外,还可以使用?传值:
1)api/students/root/?id=1 id传值为1,param为默认值1
2)api/students/root/?id=1¶m=0 id传值为1,param为传递值0
3、测试
第一种路由格式测试
第二种路由格式测试
该文参考:
https://www.cnblogs.com/CrabMan/p/10677255.html
https://www.cnblogs.com/Juvy/p/3903974.html