13

I have a Web API action that looks like the following:

[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. When I hit the following URL, I get a 404 error:

/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. How does Attribute Routing work with complex action parameters? Is it compatible with the FromUri attribute?

3
  • I am unable to repro your scenario...can you share how your route configuration looks like?...specifically the content in WebApiConfig.cs Commented Jan 17, 2014 at 21:59
  • 1
    @KiranChalla I think I accidentally solved my own problem. I typoed the sample code. I edited my question so it reflects the original code I was using. Note the {query} token in the route template. If I remove this token I believe it works as requested. Commented Jan 17, 2014 at 22:27
  • @user2719100 Would you mind clearing up the confusion please - That is, add an answer that explains the issue you had and mark it as "the answer"? TIA :) Commented Mar 18, 2014 at 1:06

2 Answers 2

7

The solution here was that the {query} token in the Route definition was superfluous. Removing it, as follows, fixed the issue:

[Route("api/query/hello")]
Sign up to request clarification or add additional context in comments.

2 Comments

Man, I so wish I could do a +5! Been struggling with this for 30 mins on a Friday Evening! Thanks!
How does this change for http post with url encoded parameters?
1

The [FromUri] attribute will be needed because you're reading from the URL. Your route should look something like:

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

/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. I'd worry about the Route Attribute after you've got it working first.

1 Comment

I simplified the example to better communicate the problem. The actual parameter class contains much more than a single string property :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.