I got the following code, and I can't get the action name to work or is something else wrong here? I want to create a custom search, where usually when you look for one object in an api you search for the id, but I would like to search for the weekday for instance, but it could really be anything.
DayController.cs :
[ActionName("Weekday")]
public IHttpActionResult GetDayWeek(string q_day) {
var day = controller.GetDay(q_day);
if (day == null) {
return NotFound();
}
return Ok(day);
}
Controller.cs :
public Day GetDay(string q_day) {
var day = dal.GetDayByWeekday(q_day);
return day;
}
Dal.cs :
public Day GetDayByWeekday(string q_day) {
var day = db.Day.Where(d = > d.Weekday == q_day).Single();
return day;
}
WebApiConfig.cs :
public static void Register(HttpConfiguration config) {
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {
id = RouteParameter.Optional
});
}
Error:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:2096/api/Day/Weekday/monday'.
</Message>
<MessageDetail>
No action was found on the controller 'Day' that matches the request.
</MessageDetail>
</Error>
Changing this:
[ActionName("Weekday")]
public IHttpActionResult GetDayWeek(string q_day) {
var day = controller.GetDay(q_day);
if (day == null) {
return NotFound();
}
return Ok(day);
}
To this:
[Route("api/day/weekday/{q_day}")]
public IHttpActionResult GetDayWeek(string q_day) {
var day = controller.GetDay(q_day);
if (day == null) {
return NotFound();
}
return Ok(day);
}
Did the trick in my testing
Some credit goes to JLevett for making me look at the Route-attribute
To explain:
The Route-attribute overrides the path to the method you're trying to call. Therefore it needs to be a full path with parameter names in it.
Do you have a method with multiple parameters this should work:
[Route("api/day/weekday/{q_day}/{w_day}")]
public IHttpActionResult GetDayWeekAndMore(string q_day, string w_day) {
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.