Multiple Routes on a Controller

前端 未结 1 694
灰色年华
灰色年华 2020-12-29 21:22

Was wondering if it was possible to have more than one route pointing to a WebApi controller?

For example I will like to have both http://domain/calculate and http:/

相关标签:
1条回答
  • 2020-12-29 21:29
    public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
                // Configure Web API to use only bearer token authentication.
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "route1",
                    routeTemplate: "calculate",
                    defaults: new { controller = "Calculator", action = "Get" });
    
                config.Routes.MapHttpRoute(
                    name: "route2",
                    routeTemplate: "v2/calculate",
                    defaults: new { controller = "Calculator", action = "Get" });
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    

    OR

    public class CalculatorController: ApiController
    {
        [Route("calculate")]
        [Route("v2/calculate")]
        public String Get() {
            return "xxxx";
        }
    }
    
    0 讨论(0)
提交回复
热议问题