【问题标题】:404 Error With MVC.NET Web APIMVC.NET Web API 出现 404 错误
【发布时间】:2016-12-30 20:12:31
【问题描述】:

我正在使用 MVC.NET 制作一个非常简单的 Web API,以从以下数据库中检索值:

CREATE TABLE [dbo].[Rates] (
    [Id]   INT          IDENTITY (1, 1) NOT NULL,
    [Code] VARCHAR (3)  NOT NULL,
    [Name] VARCHAR (50)  NOT NULL,
    [Rate] DECIMAL (5, 2) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

无论出于什么我不明白的原因,每当我编译我的解决方案并导航到 localhost:xxxxx/api 或 api/Rates(我的控制器)时,我都会收到以下错误:

“/”应用程序中的服务器错误

找不到资源。 (一个 Http 404 错误)

我不明白为什么会这样,因为它是一个新构建的 api 应用程序,使用实体框架。

下面是我的控制器和 WebApiConfig 类。也许其中之一有问题?

WebApiConfig:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using System.Net.Http.Headers;

namespace ExchangeService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "localhost:63484/api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Formatters.Remove(config.Formatters.XmlFormatter);
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

    }
}
}

ValuesController(默认保留)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace ExchangeService.Controllers
{
    [Authorize]
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

最后,我的费率控制器:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using ExchangeService.Models;

namespace ExchangeService.Controllers
{
    public class RatesController : ApiController
    {
        private ExRatesDBEntities db = new ExRatesDBEntities();

        // GET: api/Rates
        public IQueryable<Rate> GetRates()
        {
            return db.Rates;
        }

        // GET: api/Rates/5
        [ResponseType(typeof(Rate))]
        public IHttpActionResult GetRate(int id)
        {
            Rate rate = db.Rates.Find(id);
            if (rate == null)
            {
                return NotFound();
            }

            return Ok(rate);
        }

        // PUT: api/Rates/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutRate(int id, Rate rate)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

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

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

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

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Rates
        [ResponseType(typeof(Rate))]
        public IHttpActionResult PostRate(Rate rate)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Rates.Add(rate);
            db.SaveChanges();

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

        // DELETE: api/Rates/5
        [ResponseType(typeof(Rate))]
        public IHttpActionResult DeleteRate(int id)
        {
            Rate rate = db.Rates.Find(id);
            if (rate == null)
            {
                return NotFound();
            }

            db.Rates.Remove(rate);
            db.SaveChanges();

            return Ok(rate);
        }

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

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

我能想到的唯一另一点是,这个应用程序是从外部硬盘驱动器运行的。我想不出任何理由为什么这应该是一个问题,但认为这值得一提。谢谢。

【问题讨论】:

  • 能否分享 global.asax 或 startup.cs 文件并指定 web api 版本?
  • 你试过我更新的帖子了吗?如果它有效,那么请接受答案,因为它会帮助其他人更喜欢它

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


【解决方案1】:

无论出于什么我不明白的原因,每当我编译我的解决方案并导航到 localhost:xxxxx/api 或 api/Rates(我的控制器)时,我都会收到以下错误: “/”应用程序中的服务器错误 无法找到该资源。 (一个 Http 404 错误)

第一种情况是因为你没有指定API控制器,第二种情况是因为你没有指定API控制器的方法。

尝试将其称为http://localhost:63484/api/Rates/GetRates

更新:

看起来你没有正确注册你的路由,因为你同时使用 MVC 和 Web API,所以试试这些配置:

WebApiConfig 类:

public static class WebApiConfig
{
   public static void Register(HttpConfiguration config)
   {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

RouteConfig 类:

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

然后在您的 Global.asax 类中调用它们:

protected void Application_Start()
{
     ...
     //next line registers web api routes
     GlobalConfiguration.Configure(WebApiConfig.Register);
     ...
     //next line registers mvc routes
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     ...
}

【讨论】:

  • 指定方法,如api/rates/get也会导致404错误
  • @ivamax9 如果它对您有用,请为 anwser 投票,以便其他人喜欢它
【解决方案2】:

我认为您不需要列出端口。

在您的 WebApiConfig 中更改以下内容:

routeTemplate: "localhost:63484/api/{controller}/{id}"

routeTemplate: "api/{controller}/{id}"

也尝试重命名:

GetRates() to Get()

并调用:

http://localhost:63484/api/Rates

对于带有 ID 的费率,您需要进行以下更改:

    // GET: api/Rates/5
    [ResponseType(typeof(Rate))]
    public IHttpActionResult GetRate(int id)
    {
        Rate rate = db.Rates.Find(id);
        if (rate == null)
        {
            return NotFound();
        }

        return Ok(rate);
    }

    // GET: api/Rates/5
    [ResponseType(typeof(Rate))]
    public IHttpActionResult Get(int id)
    {
        Rate rate = db.Rates.Find(id);

        if (rate == null)
        {
            return NotFound();
        }

        return Ok(rate);
    }

实际上,您的 RateController 中的所有操作都需要重命名。使用与在 ValuesController 中相同的命名约定。 WepAPI 旨在通过命名的操作 Get()、Put()、Post() 等进行操作。

【讨论】:

  • 我知道这一点。我只是将端口列为“也许就是这样?”测试,但没有成功。
  • 恐怕还是没有骰子。我真的很难理解这个问题。
  • 进行了您在更新中提到的更改。这些也会导致 404。导航到 Values 控制器也会导致 404,所有 api 都不起作用。
  • 是的.. 真的难倒我。我开始怀疑是不是因为我的项目在外置硬盘上。但这对我来说毫无意义。
猜你喜欢
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
  • 2016-02-02
  • 2020-08-05
  • 2017-03-06
  • 2014-04-19
  • 2017-12-04
相关资源
最近更新 更多