Question: How to use Route in Controller Level


How to use Route in Controller Level

Answers 2
Added at 2017-01-03 11:01

Here i'm trying to call WebApi Controller using [Route] attribute

Why is http://localhost:57997/Hello/Jan/1 not a configured route while http://localhost:57997/Hello/Jan Fetching data

using a = System.Web.Http;

public IEnumerable<Department> GetDepartmets()
    var x = pro.GetDept();
    return x.ToList();

public HttpResponseMessage GetDepartmets(int id)
     if (id != null)
            var x = pro.GetDeptById(id);
            return Request.CreateResponse(HttpStatusCode.OK, x);
            return Request.CreateResponse(HttpStatusCode.NotFound);

nr: #1 dodano: 2017-01-03 11:01

Your id should match with Route id

    public HttpResponseMessage GetDepartmets(int id)
nr: #2 dodano: 2017-01-03 13:01

Here is a minimal complete verifiable example based on your original post of what the controller can look like using attribute routing.

using a = System.Web.Http;

[a.RoutePrefix("Hello/Jan")] //RoutePrefix used to group common route on controller
public MyController : ApiController {

    //...other code removed for brevity. ie: pro    

    //GET Hello/Jan
    public IHttpActionResult GetDepartmets() {
        var departments = pro.GetDept().ToList();
        return Ok(departments);

    //GET Hello/Jan/1
    [a.Route("{id:int}")] //Already have a default route. No need to make this optional
    public IHttpActionResult GetDepartmet(int id) {
         var department = pro.GetDeptById(id);
         if (department != null) {
             return Ok(department);

         return NotFound();    

Note: Make sure that attribute routing is enabled in WebApiConfig

//enable attribute routing

//...before other convention-based routes.
Source Show
◀ Wstecz