简体   繁体   中英

How to make a custom route of .NET Web API?

Ok, when we first run a web api project, we normally have this in WebApiConfig

config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{id}",
                new { id = RouteParameter.Optional }
            );

Then what if I want to make a new route other than using {controller} so it's gonna be something like this

config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/queries/{query}/{id}",
                new { id = RouteParameter.Optional }
            );

And I have my custom class to retrieve a name list like this:

public class GetNameListQuery
    {
        [HttpGet]
        public IEnumerable<String> GetNames(){ 
              return new String[] { "John" , "Adams" };
        }
    }

So that when I run the URI "mylocalhost/api/queries/GetNameList" I get the names "John" and "Adams". I'm a newbie in .NET and not sure there are any ways to do something like this. Appreciate your help. Thank you !!

in your route config:

routes.MapRoute(
      "DefaultApi2",
      "api/queries/{action}",
      new { controller = "Query" }
);

then create controller Query

public class QueryController : ApiController
{
    [HttpGet]
    public IEnumerable<String> GetNames()
    {
        return new String[] { "John", "Adams" };
    }
}

access this route : http://localhost/api/query/GetNameList

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