简体   繁体   中英

WebApi hard coded controller routing

I am trying to write a self hosted WebAPI server. I want all routes to go to a single controller. This controller can pick out the controller part of the url and use this to decide an appropriate response.

I have the following route configuration:

_configuration.Routes.MapHttpRoute
(
    name: "DefaultApi",
    routeTemplate: string.Concat("api/Home", "/{id}"),
    defaults: new { id = RouteParameter.Optional, controllerName="Home" }
);

My controller class is called "HomeController". I'm trying to redirect all URLs to it.

Here is the code for HomeController. For now I have commented out the calls to external logic (remote controller). It should just be returning a string on the Get action.

public class HomeController : ApiController
{
    private IExternalController<string> remoteController;

    public HomeController()
    {
        remoteController = GlobalKernelConfiguration.GetStandardKernel().Get<IExternalController<string>>();
    }

    public string Get()
    {
        return "HELLO FROM INTERNAL"; //remoteController.Get();
    }

    public string Get(int id)
    {
        return remoteController.Get(id);
    }

    public void Delete(int id)
    {
         remoteController.Delete(id);
    }

    public void Post(string value)
    {
        remoteController.Post(value);
    }

    public void Put(int id, string value)
    {
        remoteController.Put(id, value);
    }
}

I would expect http://localhost:9000/api/[AnythingHere] to route to the home controller but I get the following error when trying the following url: http://localhost:9000/api/Home

{"Message":"No HTTP resource was found that matches the request URI ' http://loca lhost:9000/api/Home'.","MessageDetail":"No route providing a controller name was found to match request URI ' http://localhost:9000/api/Home '"}

As @CodeCaster suggested in the comments the problem was caused by not using the correct parameter in the routing options.

This is what I had before

_configuration.Routes.MapHttpRoute ( name: "DefaultApi", routeTemplate: string.Concat("api/Home", "/{id}"), defaults: new { id = RouteParameter.Optional, controllerName="Home" } );

this is what I have now:

        public static void AddControllerRoute(string controllerName)
    {
        _configuration.Routes.MapHttpRoute
           (
               name: "DefaultApi",
               routeTemplate: string.Concat("api/Home", "/{id}"),
               defaults: new { id = RouteParameter.Optional, controller ="Home" }
           );
    }

notice that the defaults parameter was changed and now uses "controller" instead of "controllerName" this solved the problem and it's now working.

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