我正在为一些旧的存储过程创建一个API包装器以及一个新的MVC 4应用程序。到目前为止,我已经创建了这个类:
public class Event
{
public int ID;
public DateTime DateBegin;
public DateTime DateEnd;
public DateTime TimeBegin;
public int Duration;
public string Name;
public string Description;
public static IEnumerable<Event> GetEventSummary() //List<Event> GetEventSummary()
{
List<Event> events = new List<Event>();
DataTable thisDT = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string SprocName = "HE_GetEventSummary";
SqlDataAdapter thisAdapter = new SqlDataAdapter(SprocName, connection);
thisAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
thisAdapter.Fill(thisDT);
}
foreach(DataRow row in thisDT.Rows)
{
Event myEvent = new Event();
myEvent.ID = Convert.ToInt32(row["EventID"]);
myEvent.DateBegin = Convert.ToDateTime(row["EventDateBegin"].ToString());
myEvent.DateEnd = Convert.ToDateTime(row["EventDateEnd"]);
myEvent.TimeBegin = Convert.ToDateTime(row["EventTimeBegin"]);
myEvent.Duration = Convert.ToInt32(row["Duration"]);
myEvent.Name = row["EventName"].ToString();
myEvent.Description = row["EventDesc"].ToString();
events.Add(myEvent);
}
return (IEnumerable<Event>)events;
}
}
然后我从Visual Studio中提供的模板中设置这个空的API控制器:
public class EventController : ApiController
{
// GET api/event
public IEnumerable<HobbsEventsMobile.Models.Event> Get()
{
return HobbsEventsMobile.Models.Event.GetEventSummary();
//return new string[] { "value1", "value2" };
}
// GET api/event/5
public string Get(int id)
{
return "value";
}
// POST api/event
public void Post([FromBody]string value)
{
}
// PUT api/event/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/event/5
public void Delete(int id)
{
}
}
我的路线看起来像这样:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Application", action = "Index", id = UrlParameter.Optional });
}
和api路线:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "Get" }
);
}
但是当我访问http://localhost:60009/api/event
时(由api控制器中的注释指定),我收到此错误:
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: /api/event
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34009
我做错了什么?
答案 0 :(得分:3)
我们必须以下列方式在Global.asax中注册Web API路由。否则,Web API路由将无法用于解析请求。
GlobalConfiguration.Configure(WebApiConfig.Register);