简体   繁体   中英

Web api routing, URL not working

I'm currently trying to create my own Web-Api for a cryptocurrency tracker I am making.

I want to get the values from a db. The technology here is MVC5.

I have a db that contains my wallet value with a time/date attached to it, I then have an api method here:

namespace Crytocurrency_Web___Main.Controllers
{
[RoutePrefix("WalletValue")]
public class WalletValueController : ApiController
{
    readonly ApplicationDbContext dbContext = new ApplicationDbContext();

    [Route("GetAllValues")]
    [HttpGet]
    public List<WalletValue> GetAllValues()
    {
        return dbContext.Wallet.ToList();
    }
  }
}

but when I go to the address localhost:51833/WalletValue/GetAllValues I get the error:

Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its 
dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /WalletValue/GetAllValues

Here is the route config file too:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

here is document breakdown of where the controller is stored

Solution -> Controllers -> WalletValueController

Scaffolded WebAPi:

  public class WalletValuesController : ApiController
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: api/WalletValues
    public IQueryable<WalletValue> GetWallet()
    {
        return db.Wallet;
    }

    // GET: api/WalletValues/5
    [ResponseType(typeof(WalletValue))]
    public IHttpActionResult GetWalletValue(int id)
    {
        WalletValue walletValue = db.Wallet.Find(id);
        if (walletValue == null)
        {
            return NotFound();
        }

        return Ok(walletValue);
    }

    // PUT: api/WalletValues/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutWalletValue(int id, WalletValue walletValue)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != walletValue.Id)
        {
            return BadRequest();
        }

        db.Entry(walletValue).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!WalletValueExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/WalletValues
    [ResponseType(typeof(WalletValue))]
    public IHttpActionResult PostWalletValue(WalletValue walletValue)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Wallet.Add(walletValue);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = walletValue.Id }, walletValue);
    }

    // DELETE: api/WalletValues/5
    [ResponseType(typeof(WalletValue))]
    public IHttpActionResult DeleteWalletValue(int id)
    {
        WalletValue walletValue = db.Wallet.Find(id);
        if (walletValue == null)
        {
            return NotFound();
        }

        db.Wallet.Remove(walletValue);
        db.SaveChanges();

        return Ok(walletValue);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool WalletValueExists(int id)
    {
        return db.Wallet.Count(e => e.Id == id) > 0;
    }

Your Route attribute isn't being used. You have to enable attribute routing for Web API with this (in WebApiConfig.cs):

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Web API routes
        config.MapHttpAttributeRoutes();
    }
}

You can also add this to enable attribute routing for your non-API controllers (in your RegisterRoutes method):

routes.MapMvcAttributeRoutes();

Once you do that, you can remove the route.MapRoute line if you want.

That should make it work as you have it.

But note that you can put [RoutePrefix("WalletValue")] on WalletValueController , then you just need to put [Route("GetAllValues")] on your action. That saves you from having to put WalletValue/ on every action.

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