I have made a MVC 5 project and created an MVC app. Now I wan't to have an API for some of the methods and decided to create a regular web API controller. I look in the routes and they look like this default:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
By that I would mean that if I go to my localhost and say localhost/api/events then I would get the results.
Here I have my controller:
[HttpGet]
public IEnumerable<Event> GetAllEvents()
{
IEnumerable<Event> events = db.Events.ToList();
return events;
}
I haven't done anything else that creating those. No matter what I do when I call:
http://localhost:29869/api/events
Then I get 404 like there is nothing on that route. At this moment am I just up for getting it to work.
My Global.asax looks like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<ApplicationDbContext>(null);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
After changing the Global.asax then I get this message:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
ved System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() ved System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) ved System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>