Metaphor
Metaphor

Reputation: 6405

WebApi2 attribute routing URL format

I would like to route with

api/prefix/{controller}/{id}/{param}

as opposed to

api/prefix?Controller={controller}&Id={id}&Param={param}

In other words, I would prefer a URL without the name/value parameters.

The controller is defined like this:

/// <summary>
/// Employee API
/// </summary>
[System.Web.Mvc.RoutePrefix("api/employee")]
public class EmployeeController : ApiController
{
    ///<summary>
    /// Returns a collection of employees from a supplied CSV of EmployeeIds
    /// </summary>
    /// <paramref name="EmployeeIds">CSV of EmployeeIds. Pass "ALL" to include all employees. Defaults to "ALL".</paramref>
    /// <paramref name="PageSize">Number of rows to return. Defaults to all rows</paramref>
    /// <paramref name="PageNumber">Number of the page to return. Defaults to Page 0</paramref>
    /// <returns>IEnumerable<Employee></returns>
    [System.Web.Mvc.Route("id/{EmployeeIDs:alpha?}/{PageSize:int?}/PageNum:int?}")]
    public IHttpActionResult getEmployeesByIds(string EmployeeIds = "ALL",int PageSize = 0,int PageNumber = 0)
    {
        EmployeeDb db = new EmployeeDb();
        IEnumerable<Employee> e = db.getEmployeesById(EmployeeIds, PageSize, PageNumber);
        return Ok(e);
    }
}

How can I control the way the format of the URL?

Upvotes: 0

Views: 121

Answers (2)

Ajay B L
Ajay B L

Reputation: 1106

The System.Web.Http one is for Web API; the System.Web.Mvc one is for previous MVC versions. MVC is web applications, Web API is HTTP services.

RoutePrefix should be inherited from System.Web.Http.

As ApiController is from System.Web.Http, it is not able to resolve your route.

This ms-doc has good info about attribute routing.

Upvotes: 1

Akos Nagy
Akos Nagy

Reputation: 4350

You are using the System.Web.Mvc.RoutePrefix and the System.Web.Mvc.Route attributes, but you inherit from ApiController, so this is a Web API Controller, as opposed to an MVC Controller. Can you try switching over to System.Web.Http.RoutePrefix and System.Web.Http.Route?

Upvotes: 1

Related Questions