Reputation:
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);
}
Upvotes: 2
Views: 918
Reputation: 247098
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.
Upvotes: 2