简体   繁体   English

Web API路由无法正常工作(动作名称)

[英]Web API routing not working properly (action names)

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. 我想创建一个自定义搜索,通常当您在api中查找一个对象时,便会搜索ID,但是例如,我想搜索工作日,但实际上可以是任何东西。

DayController.cs : 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 : Controller.cs:

public Day GetDay(string q_day) {
    var day = dal.GetDayByWeekday(q_day);
    return day;
}

Dal.cs : Dal.cs:

public Day GetDayByWeekday(string q_day) {
    var day = db.Day.Where(d = > d.Weekday == q_day).Single();
    return day;
}

WebApiConfig.cs : 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 感谢JLevett让我看看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) {
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM