添加实体类和控制器类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;namespace WebApplication1.Models
{public class Company{public string companyCode { get; set; }public string companyName { get; set; }public string companyStatus { get; set; }public string jobGrade { get; set; }public string parentCompanyCode { get; set; }public int sort { get; set; }}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Services.Description;
using WebApplication1.Models;namespace WebApplication1.Controllers
{public class CompanyController : ApiController{Company[] companys = new Company[]{new Company { companyCode = "10", companyName = "XXX智能有限公司", companyStatus = "1", jobGrade = "测试",parentCompanyCode=null,sort=0 },new Company { companyCode = "20", companyName = "YYY科技有限公司", companyStatus = "1", jobGrade = "测试",parentCompanyCode=null,sort=1 }};public IEnumerable<Company> GetAllCompanys(){return companys;}public IHttpActionResult GetCompany(string id){var company = companys.FirstOrDefault((p) => p.companyCode == id);if (company == null){return NotFound();}return Ok(company);}}
}
那么,问题来了。访问路径我是从何得知的呢?其实是从WebApiConfig.cs文件中找到的。
WebApiConfig.cs
namespace WebApplication1
{public static class WebApiConfig{public static void Register(HttpConfiguration config){// Web API 配置和服务// Web API 路由config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(name: "DefaultApi",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);}}
}
其中,/{controller}/{action}/{id}的controller是CompanyController中的Company,action是方法名称GetAllCompanys,id是GetCompany方法的参数。