Question: How to use Route in Controller Level

Question

How to use Route in Controller Level

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

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;

[a.Route("Hello/Jan")]
public IEnumerable<Department> GetDepartmets()
{
    var x = pro.GetDept();
    return x.ToList();
}

[a.Route("Hello/Jan/{id?}")]
public HttpResponseMessage GetDepartmets(int id)
{
     if (id != null)
        {
            var x = pro.GetDeptById(id);
            return Request.CreateResponse(HttpStatusCode.OK, x);
        }
        else
            return Request.CreateResponse(HttpStatusCode.NotFound);

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

Your id should match with Route id

 [a.Route("Hello/Jan/{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
    [a.HttpGet]
    [a.Route("")]
    public IHttpActionResult GetDepartmets() {
        var departments = pro.GetDept().ToList();
        return Ok(departments);
    }

    //GET Hello/Jan/1
    [a.HttpGet]
    [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
config.MapHttpAttributeRoutes();

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