c# - 具有可选参数和查询参数的 Web Api 属性路由

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

我有这个 web api Controller :

[RoutePrefix("api/product")]
public class ProductController : ApiController
{
    [HttpGet, Route("{id?}")]
    public async Task<HttpResponseMessage> GetProduct([FromUri] string param1 = null, [FromUri] string param2 = null, Guid? id = null)
    {
        ...     
    }
}

我想通过那些 uri 访问:
api/product/?param1=something¶m2=smt
或者
api/product/7b55fcee-21e7-4b10-80e3-42b4d9cf913d?param1=something¶m2=smt

但是,第一个 uri 不起作用,路由参数的默认值未设置。
这个 uri 有效:
api/product/null?param1=something¶m2=smt
不是这个:
api/product/?param1=something¶m2=smt

我尝试为路由参数使用“string”类型,但它仍然不起作用。

是参数的顺序吗?
还是我误解了 Web Api 路由映射?

编辑: 我的 WebApiConfig.cs 不包含默认路由:

public static class EdmWebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
       if (config == null) throw new ArgumentNullException(nameof(config));

       // Attribute routing
       config.MapHttpAttributeRoutes();

       ...
       some declaration of formatters
       ...
    }
}

我应该声明一个默认路由吗?
在我看来,因为我使用了属性映射,所以我不需要这样做。

我试过这样改变我的路线:

[RoutePrefix("api")]
public class ProductController : ApiController
{

    [HttpGet, Route("product/get/{id?}")]
    public async Task<HttpResponseMessage> GetProduct([FromUri] Guid param1, [FromUri] string param2, Guid? id = null)
    {
      ...
    }
}

这个 uri api/product/get/?param1=something¶m2=smt 仍然不起作用。
(我尝试了 api/product/?param1=something¶m2=smt 与关联的路由,但不工作)

我需要在 WebApiConfig.cs 中声明默认路由吗?
您可以在 WebApiConfig.cs 中执行的操作,您应该可以在属性路由中执行,不是吗?像可选参数、约束、...

最佳答案

您的路由前缀过于具体。我相信你想要:

[RoutePrefix("api")]
public class ProductController : ApiController
{
    [HttpGet, Route("product/{id?}")]
    public async Task<HttpResponseMessage> GetProduct([FromUri] string param1 = null, [FromUri] string param2 = null, Guid? id = null)
    {
        ...     
    }
}

哪个应该适合您。路由前缀本身不是路由,因此默认路由应该不那么具体。

关于c# - 具有可选参数和查询参数的 Web Api 属性路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420613/

相关文章:

c# - 防止从第三个外部类实例化在其外部类中使用的内部类

C# WPF 调整大小问题

azure - TinyIOC 未在使用 Azure 模拟器的不同调试运行、Web api 项目上注册相同类型

c# - 如何在 C# 中实现 web api facade

c# - url.link 错误 : A route named 'Default' could not be found in the route collection. 参数名称:name

c# - WPF UserControl 如何继承 WPF UserControl?

c# - C++:数据类型为函数的 map 语法?

c# - ReadAsAsync - 抛出异常类型是接口(interface)或抽象类,无法实例化

asp.net-mvc - ASP.Net MVC 和 WebAPI 加密

c# - API 路由 : Multiple operations with path