How to configure route path to direct controller instead of getting method name

45 views Asked by At

Code img

Config img

This is a C# ASP.NET Web API program running on .NET 4.8.1.

I've tried leaving out the ActionName, and I've tried a method called Get(), but it doesn't work.

I would like to access it directly through something like

get api/user?userCode=

Route config:

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

Controller:

public class UserController : ApiController
{
    [HttpGet, ActionName("Get")]
    public object GetUserInfo(string userCode)
    {
        return new { userCode, userPwd = "123" };
    }
}
1

There are 1 answers

0
Yogi On

Eventually I searched for this solution. By saying use the Route attribute, you can customize routes for a single Controller. The prerequisite is to enable a configuration

config.MapHttpAttributeRoutes();
[RoutePrefix("api/user")]
public class UserController : ApiController
{
    [HttpGet]
    [Route("")]
    public object GetUserInfo(string userCode)
    {
        return new { userCode, userPwd = "123" };
    }
}

Successful ScreenShot Img