【问题标题】:Same method signature for two diff methods in web apiWeb api中两种不同方法的相同方法签名
【发布时间】:2018-08-05 22:41:29
【问题描述】:

它可能有重复,但我没有找到正确的解决方案,

我的网络 API,

public class SampleController : ApiController
{
    public string Get(int id)
    {
        return "value";
    }

    public string hello(int id)
    {
        return "value";
    }
} 

我的 webapiconfig,

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

我的问题是

当我调用http://localhost:1234/api/Sample/5 时,它会触发 Get(int id) 但我如何调用方法 2,即 hello(int id) ?需要更改哪些内容以及处理此类情况的最佳方法是什么?

【问题讨论】:

  • 你想调用hello方法还是Gcccet
  • 调用hello方法...localhost:1234/api/Sample/hello/5...
  • @Mittal, hello(int id) 没有命中 localhost:1234/api/Sample/hello/5
  • 更改路由模板:"api/{controller}/{action}/{id}"
  • 好的,所以如果对http://localhost:1234/api/Sample/5 的GET 是要命中hello,那么Get 是如何被访问的?

标签: c# .net asp.net-web-api asp.net-web-api-routing


【解决方案1】:

我不确定我是否正确地解决了您的问题,但如果我做到了:

你不应该用它的名字来指定函数的路由,而应该用其他方式。根据我对该主题的一点经验,我就是这样做的:

[HttpGet]
[Route("SystemInfo")] // That's the name of the route you will call
public IHttpActionResult SystemInfo()
{
    return Ok();
}

考虑检查this

所以,考虑到你的问题,它会是这样的:

[Route("Get")]
public string Get(int id)
{
    return "value";
}

[Route("hello")]
public string hello(int id)
{
    return "value";
}

【讨论】:

  • 那么这两种方法的消费网址是什么?
【解决方案2】:

TLDR:

如果您想在 Web API 中引用单个操作,请将您的路由更改为:

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

然后您可以像这样访问您的操作:localhost/api/{controller}/{action}/。更多信息请查看here,尤其是"Routing by Action Name"

原件:

您似乎期望与 MVC 控制器具有相同的行为。 MVC-Controller 的标准路由是这样的:

routeTemplate: "{controller}/{action}/{id}"

这对应于控制器的名称、要使用的方法和某种形式的输入。 ApiControllers 路由不同:

routeTemplate: "staticPart/{controller}/{id}"

如您所见,只有对单个控制器和输入的引用,以及通常类似于 /api/ 的“staticPart”

想法是您使用 RESTful 方法,将方法与不同类型的 http 方法(例如 DELETE、GET、POST、PUSH 和 PUT)连接起来

您的示例中的 Get 方法是一个特殊的方法,因为通过名称“Get”您已经告诉编译器该方法对应于 HTTP-GET。

所以要回答您的问题:要么将您的路由更改为 MVC-Controller 的路由。这样您就可以在请求中引用单个操作或使用不同的 HTTP 方法。或者您单独设置路线,如MaxB所示

您可以找到有关 Web API 路由here 的官方概述,您可以在其中找到所有可能性的示例。

【讨论】:

    猜你喜欢
    • 2010-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    相关资源
    最近更新 更多