自定义WebApi路由无法正常工作

时间:2016-02-01 22:17:41

标签: model-view-controller asp.net-web-api asp.net-mvc-5 asp.net-mvc-routing asp.net-web-api2

我正在尝试为web api控制器创建自定义路由:

<select name="clientData[first]">
  <option value="0">without</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
<input type="text" name="clientData[second]">

我希望转到[System.Web.Http.RoutePrefix("api/admin")] public class AdminApiController : BaseApiController { [Route("~/echo")] public string Echo() { return "Hello World"; } } 并接收“Hello world&#39;但是我得到了一个错误:

http://example.com/api/admin/echo

1 个答案:

答案 0 :(得分:2)

替换代字号(

方法属性上的波浪号(〜)会覆盖 控制器route prefix

[RoutePrefix("api/admin")]
public class AdminApiController : BaseApiController {
    // GET /api/admin/echo
    [HttpGet]
    [Route("echo")] 
    public string Echo() {
        return "Hello World";
    }
    // GET /echo
    [HttpGet]
    [Route("~/echo")]
    public string Echo2() {
        return "Hello World 2";
    }
}

为了安全起见,您还需要确保Enable Attribute Routing

要启用属性路由,请在配置期间调用 MapHttpAttributeRoutes 。此扩展方法在 System.Web.Http.HttpConfigurationExtensions 类中定义。

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}