简体   繁体   中英

ASP.NET Web API - how can I have one controller that will match ANY route?

I want to create a controller that looks like this:

public class GenericController : ApiController
{
    public string Get() {
        throw new Exception();
    }
}

And I want to invoke this method from any of these URL requests (assuming http://domain/ is the domain):

GET http://domain/

GET http://domain/billy

GET http://domain/susie?whatever=true

(I feel like this should be simple, but I'm unable to accomplish it with any combination of controller and WebApiConfig code.)

You can set your API route to something like this:

 routes.MapRoute(
       name: "API Default",
       template: "{name?}", new { controller = "Api"  });

and then in your controller:

[Route("{name?}")]
    [ApiController]
    public class ApiController : ControllerBase
    {
        [HttpGet]
        public string Get(string name)
        {
            // do something with name 
            return name;
        }
    }

In WebApiConfig.Register() :

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{*url}",
    defaults: new { controller = "Generic" }
);

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