简体   繁体   English

如何进行.NET Web API的自定义路由?

[英]How to make a custom route of .NET Web API?

Ok, when we first run a web api project, we normally have this in WebApiConfig 好的,当我们第一次运行Web api项目时,通常在WebApiConfig中有

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

Then what if I want to make a new route other than using {controller} so it's gonna be something like this 那如果我想使用{controller}以外的其他路线,该怎么办呢?

config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/queries/{query}/{id}",
                new { id = RouteParameter.Optional }
            );

And I have my custom class to retrieve a name list like this: 我有我的自定义类来检索这样的名称列表:

public class GetNameListQuery
    {
        [HttpGet]
        public IEnumerable<String> GetNames(){ 
              return new String[] { "John" , "Adams" };
        }
    }

So that when I run the URI "mylocalhost/api/queries/GetNameList" I get the names "John" and "Adams". 这样,当我运行URI“ mylocalhost / api / queries / GetNameList”时,我得到的名称是“ John”和“ Adams”。 I'm a newbie in .NET and not sure there are any ways to do something like this. 我是.NET的新手,不确定是否有任何方法可以执行此类操作。 Appreciate your help. 感谢您的帮助。 Thank you !! 谢谢 !!

in your route config: 在您的路由配置中:

routes.MapRoute(
      "DefaultApi2",
      "api/queries/{action}",
      new { controller = "Query" }
);

then create controller Query 然后创建控制器查询

public class QueryController : ApiController
{
    [HttpGet]
    public IEnumerable<String> GetNames()
    {
        return new String[] { "John", "Adams" };
    }
}

access this route : http://localhost/api/query/GetNameList 访问此路由: http:// localhost / api / query / GetNameList

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

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