具有属性路由的多个GET不好? [英] Multiple GET no good w/ Attribute Routing?

查看:134
本文介绍了具有属性路由的多个GET不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是对的:

/api/MyDataController.cs

/api/MyDataController.cs

public class MyDataController: ApiController
{
  [HttpGet]
  [Route("GetOne")]  
  public IHttpActionResult GetOne() { }  // works w/o GetTwo

  [HttpGet]
  [Route("GetTwo")]
  public IHttpActionResult GetTwo() { }
}

.js

$http({method: 'GET', url: '/api/MyData/GetOne'})... //works w/o GetTwo
$http({method: 'GET', url: '/api/MyData/GetTwo'})... 

这篇文章相同, API版本为

Same as this post, API version is

<package id="Microsoft.AspNet.WebApi" version="5.2.3"
targetFramework="net461" />

呼叫一个两个都抱怨 GetOne

找到了多个与请求匹配的动作:类型为GetOne MyWeb.API.MyDataControllerGetOne的类型 MyWeb.API.MyDataController"

"Multiple actions were found that match the request: GetOne on type MyWeb.API.MyDataControllerGetOne on type MyWeb.API.MyDataController"

如果从Api控制器中重新删除GetTwo()则可以使用.

It works if rem-out GetTwo() from Api controller.

推荐答案

这似乎是应用程序仍在使用基于约定的路由.

This looks like the application is still using convention-based routing.

发生冲突的原因是因为默认的基于约定的路由模板api/{controller}/{id}通常不提供像api/{controller}/{action}/{id}这样的操作参数.如果您希望在使用之前提供的模板时通过常规路由使发布操作起作用.

The reason for the clash is because the default convention-based route template api/{controller}/{id}does not usually provide an action parameter like this api/{controller}/{action}/{id}. If you want to get post actions to work via convention-routing when use the template provided before.

如果要使用属性路由,则需要在WebApiConfig.cs文件中启用属性路由,以允许Rout Atrribute工作.

If you want to use attribute routing instead then you need to enable attribute routing in the WebApiConfig.cs file in order to allow the Rout Atrribute to work.

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

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

您还需要更新路线以获取想要的东西

You would also need to update your routes to get what you want

[RoutePrefix("MyData")]
public class MyDataController: ApiController {

    //GET MyData/GetOne
    [HttpGet]
    [Route("GetOne")]  
    public IHttpActionResult GetOne() { } 

    //GET MyData/GetTwo
    [HttpGet]
    [Route("GetTwo")]
    public IHttpActionResult GetTwo() { }
}

此处的属性路由阅读 查看全文

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