1. 修改WebApiConfig.cs中路由路径
问题:webapi的默认路由并不需要指定action的名称(WebApi的默认路由是通过http的方法get/post/put/delete去匹配对应的action),
但默认路由模板无法满足针对一种资源一种请求方式的多种操作。
解决:打开App_Start文件夹下,WebApiConfig.cs ,修改路由,加上{action}/ ,其中,{id}是api接口函数中的参数。。
这样就可以在api接口中通过接口函数名,来导向我们希望调用的api函数,否则,只能通过controller来导向,就可能会造成有相同参数的不同名函数冲突。
View Code
2. 添加控制器
a. 右键Controllers文件夹---添加---控制器)
b. 左边选择web API页签,右边选择控制器(空)
c. 给控制器命名(只需要改高亮部分,后面的Controller保留)
3. 功能测试
a. 右键Models文件夹,选择新建类
public class Game{public string name { get; set; }public string director { get; set; }public string actor { get; set; }public string type { get; set; }public int price { get; set; }}public class Product{public int Id { get; set; }public string Name { get; set; }public string Category { get; set; }public decimal Price { get; set; }}
b. 右键Controllers文件夹,增加控制器
public class TestController : ApiController{Game[] myGame = new Game[]{new Game { name="one",director="one.1",actor="a",type="动漫",price=28},new Game { name="two",director="two.1",actor="b",type="惊悚",price=32},new Game { name="three",director="three.1",actor="c",type="惊悚",price=28},new Game { name="four",director="four.1",actor="d",type="动漫",price=28}};public IEnumerable<Game> GetAllMovies(){return myGame;}public IHttpActionResult GetMovie(string name) //异步方式创建有什么作用 {var mov = myGame.FirstOrDefault((p) => p.name == name);if (myGame == null){return NotFound();}return Ok(myGame);}}public class ProductsController : ApiController{Product[] products = new Product[]{new Product { Id = 1, Name = "Apple Soup", Category = "Groceries", Price = 1 },new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 4.35M },new Product { Id = 3, Name = "Linda", Category = "Hardware", Price = 11.2M }};public IEnumerable<Product> GetAllProducts(){return products;}public IHttpActionResult GetProduct(int id){var product = products.FirstOrDefault((p) => p.Id == id);if (product == null){return NotFound();}return Ok(product);}}public class ParaController : ApiController{[HttpGet]public string ParaExample(string param1, int param2){string res = "";res = param1 + param2.ToString();//其他操作return res;}}
c. 点击运行,在URL后加具体action路径
结果如下:
d. 去掉xml返回格式、设置json返回
public static class WebApiConfig{public static void Register(HttpConfiguration config){// Web API 配置和服务// Web API 路由 config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(name: "DefaultApi",//修改路由,加上{action}/ ,这样就可以在api接口中通过接口函数名,来导向我们希望调用的api函数,//否则,只能通过controller来导向,就可能会造成有相同参数的不同名函数,冲突。其中,{id}是api接口函数中的参数routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });//去掉xml返回格式、设置json字段命名采用var appXmlType =config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);}}
e. 统一返回值格式
public class RtnValue{private string msgModel = "{{\"code\":{0},\"message\":\"{1}\",\"result\":{2}}}";public RtnValue(){}public HttpResponseMessage MsgFormat(ResponseCode code, string explanation, string result){string r = @"^(\-|\+)?\d+(\.\d+)?$";string json = string.Empty;if (Regex.IsMatch(result, r) || result.ToLower() == "true" || result.ToLower() == "false" || result == "[]" || result.Contains('{')){json = string.Format(msgModel, (int)code, explanation, result);}else{if (result.Contains('"')){json = string.Format(msgModel, (int)code, explanation, result);}else{json = string.Format(msgModel, (int)code, explanation, "\"" + result + "\"");}}return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };}}public enum ResponseCode{操作失败 = 00000,操作成功 = 10000,}public class CheckController : ApiController{//检查用户名是否已注册private RtnValue tool = new RtnValue();[HttpGet]public HttpResponseMessage CheckUserName(string _userName){int num = UserInfoGetCount(_userName);//查询是否存在该用户if (num > 0){return tool.MsgFormat(ResponseCode.操作失败, "不可注册/用户已注册", "1 " + _userName);}else{return tool.MsgFormat(ResponseCode.操作成功, "可注册", "0 " + _userName);}}private int UserInfoGetCount(string username){//return Convert.ToInt32(SearchValue("select count(id) from userinfo where username='" + username + "'"));return username == "admin" ? 1 : 0;}}