Web api路由,URL无法正常工作

时间:2017-12-22 18:22:14

标签: c# asp.net-mvc asp.net-web-api

我目前正在尝试为我正在制作的加密货币跟踪器创建自己的Web-Api。

我想从db中获取值。这里的技术是MVC5。

我有一个包含我的钱包值的数据库,附有时间/日期,然后我在这里有一个api方法:

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();
    }
  }
}

但是当我去地址时     localhost:51833 / WalletValue / GetAllValues我收到错误:

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

这也是路由配置文件:

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 }
        );
    }

这里是控制器存储位置的文档细分

解决方案 - &gt;控制器 - &gt; 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;
    }

1 个答案:

答案 0 :(得分:3)

您的Route属性未被使用。您必须使用此方法为Web API启用属性路由(在WebApiConfig.cs中):

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

您也可以添加此项以启用非API控制器的属性路由(在RegisterRoutes方法中):

routes.MapMvcAttributeRoutes();

执行此操作后,您可以根据需要删除route.MapRoute行。

这应该让它像你拥有它一样工作。

但请注意,您可以将[RoutePrefix("WalletValue")]放在WalletValueController上,然后您只需将[Route("GetAllValues")]置于您的操作上即可。这样您就不必为每个操作添加WalletValue/