简体   繁体   中英

ASP.NET Web API 5.2.3 Attribute Route returning 404

I've got an ASP.NET Web API project that I'm working on. I've got an APIController called SpellbookController that has basic CRUD operations to an EntityFramework repository.

However, when I try to add a method that takes a parameter that's not an id, I can't seem to get it to route correctly.

Here's what it looks like:

// GET: api/Spellbooks/user@email.com
[ResponseType(typeof(List<Spellbook>))]
[Route("api/Spellbooks/{username}")]
public IHttpActionResult GetSpellbook(string username)
{
    List<Spellbook> spellbooks = db.Spellbooks.Where(x=>x.Username == username).ToList();
    if (spellbooks == null)
    {
        return NotFound();
    }

    return Ok(spellbooks);
}

So I'm trying to hit http://localhost:xxxx/api/Spellbooks/emailaddress , but I get a 404 every time.

It's definitely an APIController, and I have config.MapHttpAttributeRoutes(); turned on.

What am I missing?

Where is your username parameter?

Your call should looks like this-

 http://localhost:xxxx/api/Spellbooks/emailaddress/David

Update

Try to declare the parameter as string {username:string}

Update 2

The problem is with your '.' as you can see in this link . You can send the email without the point in the parameter and then replace ite back to you regular mode or you can use all the good advice that the link provide.

If you step through it, do you get a value when looking at username ? Or is it always null?

If your route is not working, a simple way to debug the route is to make a request to http://localhost:xxxx/api/Spellbooks/?emailaddress=thisemailaddress and see if you can get a response. In fact, from a REST standard, it can be argues that it's a cleaner route, since you will be returning a collection of elements, rather than a single object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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