ApiController GET Action 命名

问题描述 投票:0回答:3

我有一个具有多个 GET 操作的 ApiController。问题是我不想在名称开头没有“Get”的情况下命名我的操作。

例如,我可以有一个名为“GetImage”的操作,它会正常工作。 如果我将其命名为“UpdateImage”,它不会调用该操作,因为它可能需要在操作名称的开头有一个明确的“Get”。

我可以通过为我想要使用的每个操作定义不同的路线来解决它,但我确信一定有一种更简单的方法来实现它。

我也尝试了 [HttpGet] 属性,但不幸的是它没有成功。

我的路线配置:

    routes.MapHttpRoute(
        name: "ImagesApi",
        routeTemplate: "api/images/{action}/{id}",
        defaults: new { controller = "ImageStorageManager",id = RouteParameter.Optional }
    );

我通过

api/images/GetImage
api/images/UpdateImage

访问它
asp.net-mvc api asp.net-web-api asp.net-routing
3个回答
6
投票

我创建不仅仅针对单个对象的 api 控制器的方式可能会对您有所帮助。我从 John Papa 在 PluralSight 上的 SPA 演讲中获得了该方法(我强烈建议学习单页应用程序时使用该方法)。他还在其中一个模块中介绍了这一点。

它有 2 个部分。

第 1 部分,设置路线以执行 2 个正常场景,然后添加第三个以满足我的需求:

// ex: api/persons
routes.MapHttpRoute(
            name: ControllerOnly,
            routeTemplate: "api/{controller}"
        );// ex: api/sessionbriefs

//  ex: api/persons/1
routes.MapHttpRoute(
            name: ControllerAndId,
            routeTemplate: "api/{controller}/{id}",
            defaults: null, //defaults: new { id = RouteParameter.Optional } //,
            constraints: new { id = @"^\d+$" } // id must be all digits
        );

// ex: api/lookups/all
// ex: api/lookups/rooms
routes.MapHttpRoute(
            name: ControllerAction,
            routeTemplate: "api/{controller}/{action}"
        );

第 2 部分,在查找控制器中(以 John Papa 为例),向方法添加 ActionName 属性:

    // GET: api/lookups/rooms
    [ActionName("rooms")]
    public IEnumerable<Room> GetRooms()
    {
        return Uow.Rooms.GetAll().OrderBy(r => r.Name);
    }

    // GET: api/lookups/timeslots
    [ActionName("timeslots")]
    public IEnumerable<TimeSlot> GetTimeSlots()
    {
        return Uow.TimeSlots.GetAll().OrderBy(ts => ts.Start);
    }

2
投票

用 [HttpGet] 装饰你的动作。有关原因以及 ApiController 路由如何工作的详细信息,请参阅 http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api


0
投票
在 .net core 中 - 您可以在 ImagesController 中执行以下操作来临时映射操作:

// api/images/{id} [HttpGet("{id}")] public ActionResult<string> Get(string id) { ... } // api/images/myaction/{id} [HttpGet("myaction/{id}")] public ActionResult<string> GetMyAction(string id) { ... }
    
© www.soinside.com 2019 - 2024. All rights reserved.