0

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>

2 Answers2

0

Change your action to

[HttpGet]
public IEnumerable<Event> Get()
{
    IEnumerable<Event> events = db.Events.ToList();
    return events;
}

This should work, also you can use attribute routing to add the specific route you would like to hit the action I.e.

[HttpGet]
[Route("/Events")]
public IEnumerable<Event> GetAllEvents()
{
    IEnumerable<Event> events = db.Events.ToList();
    return events;
}

What's the name of your controller, the default route will find the controller and then select the action that matches the http verb (get) and any parameters, in your case no parameters so localhost:29869/api/Events will call the get prefixed method from the EventsController . The route attribute will allow you to specify the url that will select the action so [Route("api/Events")] will map localhost:29869/api/Events to the action.

BhavO
  • 2,406
  • 1
  • 11
  • 13
  • For some reason this doesn't work. I have tried this but it still gives a 404 –  Jul 04 '15 at 09:39
  • Change order of config changes to above – BhavO Jul 04 '15 at 09:57
  • See the new change that has happened after I changed the config –  Jul 04 '15 at 10:05
  • Revert the config change, did you try the route attribute – BhavO Jul 04 '15 at 10:23
  • What's the name of your controller, the default route will find the controller and then select the action that matches the http verb (get) and any parameters, in your case no parameters so http://localhost:29869/api/Events will call the get prefixed method from the EventsController . The route attribute will allow you to specify the url that will select the action so [Route("api/Events")] will map http://localhost:29869/api/Events to the action. – BhavO Jul 04 '15 at 11:23
  • 1
    Are you sure the port is 29869 for your application? It can change sometimes through the course of development. – Origin Jul 04 '15 at 12:07
  • You wouldn't get a 404 otherwise, when u debug it will launch with the correct port – BhavO Jul 04 '15 at 12:13
  • you can refer to Ian Mercer and gentiane's anwser in http://stackoverflow.com/questions/19969228/ensure-that-httpconfiguration-ensureinitialized. if you have no port conflict. – paul cheung Jul 04 '15 at 12:17
  • @BhavO - you would think so, but despite this I have come against issues with this. Sometimes VS will also have stagnant versions of the website running in IIS, which makes it incredibly hard to debug :) – Origin Jul 04 '15 at 14:06
  • The answer you came with @paulcheung was the right one. If you create an answer then I will close this problem. Thanks for the help and advises everyone! :-) –  Jul 04 '15 at 15:57
0

you can refer to Ian Mercer and gentiane's anwser in Ensure that HttpConfiguration.EnsureInitialized() if you have no port conflict.

hope it helps.

Community
  • 1
  • 1
paul cheung
  • 748
  • 2
  • 13
  • 32