尝试运行此脚本时出现 500 错误。我在 asp.net mvc4 中设置了一个演示项目,带有一个小型 web api 控制器和默认的 home 控制器。这是我的 api 控制器:
namespace MyTrainingApi.Controllers
{
public class CoursesController : ApiController
{
//for demo mock data, would pull from dbContext here.
static List<Course> _courses = InitCourses();
private static List<Course> InitCourses()
{
var ret = new List<Course>();
ret.Add(new Course { id = 0, name = "HTTP Fundamentals" });
ret.Add(new Course { id = 1, name = "HTTP Fundamentals Part 2" });
ret.Add(new Course { id = 2, name = "HTTP Fundamentals Part 3" });
ret.Add(new Course { id = 3, name = "How to bake a cake" });
return ret;
}
//uri: /api/courses/
public IEnumerable<Course> Get()
{
return _courses;
}
//uri: /api/courses/{id}
public Course Get(int id)
{
Course ret = null;
ret = (from c in _courses where c.id == id select c).FirstOrDefault();
if (ret == null)
{
//TODO: return 404
}
return ret;
}
public Course Post(Course newCourse)
{
newCourse.id = _courses.Count();
_courses.Add(newCourse);
//TODO: return 202
return newCourse;
}
}
public class Course
{
public int id { get; set; }
public string name { get; set; }
}
}
这是我的 HomeController:
namespace MyTrainingApi.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
}
public ActionResult Course(int id)
{
return View(id);
}
public ActionResult Create()
{
return View();
}
}
}
所以我有三个我正在试验的视图:索引是所有课程的列表,课程是基于 id 的一门课程,创建应该返回一些信息并添加课程。Create 视图是我在这里遇到的问题。这是视图代码:
错误消息说:
没有 MediaTypeFormatter 可用于从媒体类型为“未定义”的内容中读取“课程”类型的对象。