asp.net-mvc – 路由在Asp.net Mvc 4和Web Api

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 路由在Asp.net Mvc 4和Web Api前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我可以一起使用以下两个路由规则吗?
config.Routes.MapHttpRoute(
    name: "ActionApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional } );

config.Routes.MapHttpRoute(
    name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
);

说控制器是= FruitApiController:ApiController和我希望有以下

> List< Fruit> Get()= api / FruitApi /
> List< Fruit> GetSeasonalFruits()= api / FruitApi / GetSeasonalFruit
> Fruit GetFruits(string id)= api / FruitApi / 15
> Fruit GetFruitsByName(string name)= api / FruitApi / GetFruitsByName / apple

请帮我这个。谢谢

解决方法

你可以有几个路线:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "ApiById",defaults: new { id = RouteParameter.Optional },constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByName",routeTemplate: "api/{controller}/{action}/{name}",defaults: null,constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByAction",routeTemplate: "api/{controller}/{action}",defaults: new { action = "Get" }
        );
    }
}
原文链接:https://www.f2er.com/aspnet/254745.html

猜你在找的asp.Net相关文章