简体   繁体   English

ASP.NET MVC API路由

[英]ASP.NET MVC API Routing

I am trying to create a route to an API in my ASP.NET MVC app. 我正在尝试在ASP.NET MVC应用程序中创建到API的路由。 Examples of calls to this API look like this: 对该API的调用示例如下所示:

/MyApp/api/lookup/person?i1=123&i2=test
/MyApp/api/lookup/product?i1=597&i2=1234
/MyApp/api/lookup/order?i1=1&i2=597

The general structure of the route looks like this: 路线的一般结构如下:

/{AppRoot}/api/lookup/{someKey}?i1={value1}&i2={value2}

I added a route in my WebApiConfig.cs file that looks like this: 我在WebApiConfig.cs文件中添加了一条如下所示的路由:

config.Routes.MapHttpRoute(
  name: "LookupApi",
  routeTemplate: "api/lookup/{action}",
  defaults: new { controller = "LookupApi", action = "Index" }
);

I then have a controller defined like this: 然后,我有一个这样定义的控制器:

public class LookupApiController
{
  [HttpGet]
  public async Task<IHttpActionResult> Index()
  {
    return Ok();
  }
}

When I set a breakpoint in the Index action, it is not getting called. 当我在Index操作中设置一个断点时,它不会被调用。 I do not understand why. 我不理解为什么。 I wish there was an easy way to see what Controller Action was called for a given route and which line of code that mapped to. 我希望有一种简单的方法来查看给定路由所调用的Controller Action以及映射到的代码行。 Either way, how do I resolve this issue of my Lookup action not getting called? 无论哪种方式,如何解决我的Lookup操作未得到调用的问题?

From what you defined routeTemplate: "api/lookup/{action}" , for url like /MyApp/api/lookup/person?i1=123&i2=test , it will take person as action name, and will try to find an action called person in the LookupApiController which doesn't exist. 根据您定义的routeTemplate: "api/lookup/{action}" ,对于/MyApp/api/lookup/person?i1=123&i2=test这样的网址,它将以person作为动作名称,并尝试查找名为personLookupApiController不存在。

I am not sure if you want to create those actions to fit your structure or not, a straight forward way to make the example url to hit the Index action is to change your route to: 我不确定是否要创建适合您的结构的操作,使示例url进入Index操作的直接方法是将您的路线更改为:

config.Routes.MapHttpRoute(
  name: "LookupApi",
  routeTemplate: "api/lookup/{someKey}",
  defaults: new { controller = "LookupApi", action = "Index" }
);

In this way the person in your url will no longer represents the action name, and you can grab the value as parameter in the Index action: 这样,您网址中的person将不再代表操作名称,您可以在Index操作中获取该值作为参数:

public class LookupApiController
{
  [HttpGet]
  public async Task<IHttpActionResult> Index(string someKey)
  {
    //DO something
    return Ok();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM