添加一个明确的行动路线的ASP.NET Web API控制器 [英] Adding an explicit action route to ASP.NET Web API Controller

查看:93
本文介绍了添加一个明确的行动路线的ASP.NET Web API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Web API项目中的 ApiController ,提供了一个用户端点有下列行为

I have an ASP.NET Web API project with an ApiController that provides a User endpoint with the following actions:

GET /api/User
POST /api/User
DELETE /api/user

我要提供以下端点:

I want to provide the following endpoint:

GET /api/user/metrics

然而,当我确定,像这样的控制器动作:

However, when I define the controller action like so:

[HttpGet]
public HttpResponseMessage Metrics()
{
    return null;
}

我得到的多个操作中发现匹配的要求,即错误消息。

我明白这违反了纯粹的REST API的定义,但是这是我想做到这一点。我想我有一个映射路径HTTP来解决这个问题,但我已经尝试了一些路线,我无法得到它的工作。我应该我的路线是什么样子?

I understand this violates the definition of a "pure" REST API but this is how I would like to do it. I imagine I have to solve this problem by mapping an HTTP route, but I have tried a few routes and I can't get it to work. What should my route look like?

推荐答案

默认路由不包括动作。

The default route does not include the action.

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

有选择基于控制器,HTTP谓词和参数,或缺乏参数的动作,在路径。因此,它是找到正确的控制器和寻找不带参数的GET动作。发现两个。

It selects actions based on the controller, HTTP verb and the parameter, or lack of parameter, in the route. So, it is finding the correct controller and looking for a GET action with no parameter. It finds two.

您应该添加,包括操作的附加路由。这可通过基于属性路由完成如基兰提到或通过基于惯例路由。对于基于路由的公约,该航线通常放置在的Application_Start() WebApiConfig.cs 的方法。更具体的路线一般途径之前去,这样你的路由看起来是这样的:

You should add an additional route that includes the action. This is either done with attribute based routing as Kiran mentioned or by convention based routing. For convention based routing, the route is typically placed in the Application_start() method of WebApiConfig.cs. More specific routes go before general routes, so your routes would look something like this:

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

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

这篇关于添加一个明确的行动路线的ASP.NET Web API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆