简体   繁体   English

如何将ASP.NET Web API属性路由与复杂对象参数一起使用?

[英]How do I use ASP.NET Web API Attribute Routing with a complex object parameter?

I have a Web API action that looks like the following: 我有一个Web API操作,如下所示:

[HttpGet]
[Route("api/query/hello/{query}")]
public HttpResponseMessage Hello([FromUri]Query query)
{
    return null;
}

where the Query class has a public string property named QueryText . 其中Query类具有名为QueryText的公共字符串属性。 When I hit the following URL, I get a 404 error: 当我点击以下网址时,收到404错误:

/api/query/hello?QueryText=bacon

This worked before I started using Attribute Routing. 这在我开始使用属性路由之前有效。 If I have no parameters or primitive type parameters, I can get Attribute Routing to work. 如果我没有参数或基本类型参​​数,我可以使属性路由工作。 But with a complex parameter, I get 404s. 但是对于复杂的参数,我得到404s。 How does Attribute Routing work with complex action parameters? 属性路由如何使用复杂的操作参数? Is it compatible with the FromUri attribute? 它与FromUri属性兼容吗?

The solution here was that the {query} token in the Route definition was superfluous. 这里的解决方案是路由定义中的{query}标记是多余的。 Removing it, as follows, fixed the issue: 删除它,如下,修复了问题:

[Route("api/query/hello")]

The [FromUri] attribute will be needed because you're reading from the URL. 由于您正在从URL中读取,因此需要[FromUri]属性。 Your route should look something like: 您的路线应该类似于:

public HttpResponseMessage Hello([FromUri]Query query)
{
    //Implement whatever
    return null;
}

/api/{Controller Name}/hello?QueryText=bacon / api / {Controller Name} / hello?QueryText = bacon

Should then work correctly. 应该正常工作。

The model binder will take whatever query parameters you provided then try to bind whatever is inside that Query object. 模型绑定器将获取您提供的任何查询参数,然后尝试绑定Query对象内的任何内容。 I'd worry about the Route Attribute after you've got it working first. 在你首先工作后我会担心路线属性。

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

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