webapi 返回json及route设置
1、返回json 修改App_Start/webapiconfig
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
2、配置路由。在controller上面加filter [RoutePrefix("api/EquipmentApi")],在action上面加 [Route("GetEquipmentsOfStoreHouse")]
则访问时用http://aaaaaa/api/EquipmentApi/GetEquipmentsOfStoreHouse?begin=0&pagesize=8&stateId=1
[RoutePrefix("api/EquipmentApi")]
public class EquipmentApiController : ApiController
{
[Route("GetEquipmentsOfStoreHouse")]
[HttpGet]
public ApiResponse<List<EquipmentViewModel>> GetEquipments(int begin, int pageSize, byte? stateId = null)
{
};
}
3、如上面的action参数默认值,则不用传stateId这个参数,http://aaaaaa/api/EquipmentApi/GetEquipmentsOfStoreHouse?begin=0&pagesize=8