【问题标题】:How to make a custom route of .NET Web API?如何制作.NET Web API 的自定义路由?
【发布时间】:2019-07-31 16:39:05
【问题描述】:

好的,当我们第一次运行一个web api项目时,我们通常在WebApiConfig中有这个

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

如果我想创建一个新路由而不是使用 {controller} 会是这样的

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

我有我的自定义类来检索这样的名单:

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

因此,当我运行 URI“mylocalhost/api/queries/GetNameList”时,我会得到名称“John”和“Adams”。我是 .NET 的新手,不确定有什么方法可以做这样的事情。感谢你的帮助。谢谢!!

【问题讨论】:

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


【解决方案1】:

在您的路线配置中:

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

然后创建控制器查询

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

访问这条路线:http://localhost/api/query/GetNameList

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2015-11-10
    • 1970-01-01
    相关资源
    最近更新 更多