简体   繁体   中英

How does the controller portion of the routing path get configured in .NET Web API

I have an existing .NET 4 console application which I want to start exposing a REST API. I'm using the Microsoft self host Web API library to have it expose that API, but I'm having trouble understanding how the routing path gets developed.

Here is an example of a controller, which should expose some database objects my console application already handles:

public class UserController : ApiController
{
    UserInformation[] users;

    public IEnumerable<UserInformation> GetAllUsers()
    {
         // snip.
    }

    public UserInformation GetUserById(int id)
    {
         // snip.
    }

}

And I'm exposing my API in Program.cs like so:

var config = new HttpSelfHostConfiguration("http://localhost:8800");
config.Routes.MapHttpRoute(
    "API Default", "api/{controller}/{id}",
    new { id = RouteParameter.Optional });

using (var server = new HttpSelfHostServer(config)) { // code }

Given the above code, I'd expect that I could get resources by making http requests like http://localhost:8800/api/users and http://localhost:8800/api/users/1 , but those don't seem to work. How does the controller part of the GET request get created? It doesn't seem like users is the correct routing path for the API, but I'm not sure what goes there.

Thanks for any help

That's because your controller is called UserController and not UsersController . Either rename your controller to UsersController or modify your request to go to http://localhost:8800/api/user .

This should solve the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM