我有一个支持MVC的webforms项目。我创建了一个WEB API 2控制器,它使用的模型类首先使用EF数据库生成,将SQL表转换为实体模型。当我启动我的应用程序时,控制器无法按预期工作。尝试访问api时,我得到以下内容:
HTTP错误404.0 - 未找到 您要查找的资源已被删除,名称已更改或暂时不可用。
我的Controller类如下:
namespace YuClone.Controllers {
public class VideosController : ApiController
{
private YuCloneContext db = new YuCloneContext();
// GET: api/Videos
public IQueryable<video> Getvideos()
{
return db.videos;
}
// GET: api/Videos/5
[ResponseType(typeof(video))]
public IHttpActionResult Getvideo(long id)
{
video video = db.videos.Find(id);
if (video == null)
{
return NotFound();
}
return Ok(video);
}
// PUT: api/Videos/5
[ResponseType(typeof(void))]
public IHttpActionResult Putvideo(long id, video video)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != video.videoid)
{
return BadRequest();
}
db.Entry(video).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!videoExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Videos
[ResponseType(typeof(video))]
public IHttpActionResult Postvideo(video video)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.videos.Add(video);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = video.videoid }, video);
}
// DELETE: api/Videos/5
[ResponseType(typeof(video))]
public IHttpActionResult Deletevideo(long id)
{
video video = db.videos.Find(id);
if (video == null)
{
return NotFound();
}
db.videos.Remove(video);
db.SaveChanges();
return Ok(video);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool videoExists(long id)
{
return db.videos.Count(e => e.videoid == id) > 0;
}
} }
可以采取哪些措施来解决这个问题?
修改
这是在WebApiConfig中配置路由的方式:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
在Global.aspx中的application_start方法中注册为:
RouteConfig.RegisterRoutes(RouteTable.Routes);
我用来访问资源的网址是:
http://localhost:5958/api/videos
答案 0 :(得分:0)
确保在RouteConfig.RegisterRoutes
之后拨打WebApiConfig.Register
。像这样:
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);