简体   繁体   English

许多ASP.net WebAPI路由

[英]Many ASP.net WebAPI routes

Just starting a project which is going to use a lot of WebAPI endpoints and had some questions about the routes. 刚开始一个项目,该项目将使用许多WebAPI端点,并且对路由有一些疑问。 Since there are going to be many methods with different parameter names, the solution I've thought about is adding different routes with varying parameter names. 由于将有许多方法具有不同的参数名称,因此我考虑过的解决方案是添加具有不同参数名称的不同路由。

The problem is all the methods I define in various ApiController classes have the signature similar to 问题是我在各种ApiController类中定义的所有方法的签名都类似于

public string SomeMethod(string token, string id);
{
    //method body
}

I'd like to have other methods with: 我想使用其他方法:

public string SomeMethod1(string token, string logType)
{
    //method body
}
public string SomeMethod2(string token, string name)
{
    //method body
} ....etc

I would like to avoid having to define every method with the parameter name as "id", so that the routes would match and would bind to the respective method in the ApiController class. 我想避免必须将参数名称定义为“ id”的每个方法定义为使路由匹配并绑定到ApiController类中的相应方法。

Is this an acceptable practice to add many routes in WebAPI routes config, so that varying parameters with different parameter name would bind to the correct method. 在WebAPI路由配置中添加许多路由是一种可接受的做法,这样,具有不同参数名称的不同参数将绑定到正确的方法。

Would it affect the overall performance, if I've many routes in the config class? 如果我在config类中有很多路由,会影响整体性能吗?

Is there a better way to achieve what I'm trying to pull here? 有没有更好的方法来实现我要在这里实现的目标?

It sounds like your main concern is the trade off between the a) need for multiple route definitions versus b) a single route with the 'id' parameter name. 听起来您主要关心的是在a)需要多个路由定义与b)具有'id'参数名称的单个路由之间进行权衡。 While I doubt the performance hit of many routes is a big deal I would lean toward a single route definition for the sake of having less code. 尽管我怀疑许多路由的性能影响很大,但为了减少代码数量,我倾向于使用单个路由定义。 You don't have to call the parameter 'id', but it would need to be the same. 您不必调用参数“ id”,但是它必须相同。 Perhaps something generic like 'argument': 也许像“参数”这样的通用名称:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{token}/{argument}",
    defaults: new { controller = "Blah", action = "SomeMethod" });

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

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