【问题标题】:WebApi. Custom route not working as expectedWebAPI。自定义路线未按预期工作
【发布时间】:2017-04-29 10:20:28
【问题描述】:

我正在尝试使用包含三种方法的[RoutePrefix("front")] 向控制器添加自定义路由:

[HttpGet]
[ResponseType(typeof(SparePartsFrontDTO))]
public async Task<IHttpActionResult> Get()
{
    ...
}

[HttpGet]
[ResponseType(typeof(IEnumerable<SparePartSearchDTO>))]
public async Task<IHttpActionResult> Get(string filter)
{
    ...
}

[HttpGet]
[Route("categories")]
[ResponseType(typeof(IEnumerable<DeviceCategoryDTO>))]
public async Task<IHttpActionResult> GetCategories()
{
    ...
}

但是当我通过路由api/front/categories调用方法时,而不是自定义路由,调用了默认的get方法。

这是 WebApi 配置:

config.MapHttpAttributeRoutes();
config.MessageHandlers.Add(new PreflightRequestsHandler());
config.SuppressDefaultHostAuthentication();    
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api-routing


    【解决方案1】:

    路由前缀需要有所需的模板,其他操作也需要Route 属性。

    [RoutePrefix("api/front")]
    public class MyController : ApiController {
    
        [HttpGet]
        [Route("")] // matches GET api/front
        [ResponseType(typeof(SparePartsFrontDTO))]
        public async Task<IHttpActionResult> Get() {
            //...
        }
    
        [HttpGet]
        [Route("filter/{filter}")] // matches GET api/front/filter/anything-here
        [ResponseType(typeof(IEnumerable<SparePartSearchDTO>))]
        public async Task<IHttpActionResult> Get(string filter) {
            //...
        }
    
        [HttpGet]
        [Route("categories")] //matches GET api/front/categories
        [ResponseType(typeof(IEnumerable<DeviceCategoryDTO>))]
        public async Task<IHttpActionResult> GetCategories() {
            //...
        }
    }
    

    参考Attribute Routing in ASP.NET Web API 2 : Route Prefixes

    【讨论】:

    • 我收到错误消息:尝试创建像“FrontController”这样的控制器时发生错误。确保控制器有一个没有参数的公共构造函数。
    • @andrey.shedko,这是框架尝试创建控制器并遇到问题时发生的标准错误。如果您使用依赖注入 (IDependencyResolver),那么您需要确保所有依赖项都已正确注册到您的 DI 容器中。
    • 是的。我正在使用 DI,但我认为它不相关,因为在我尝试创建自定义路由之前 DI 没有问题。
    猜你喜欢
    • 2014-03-26
    • 1970-01-01
    • 2022-11-11
    • 2018-03-09
    • 1970-01-01
    • 2017-01-01
    • 2021-10-22
    • 2015-11-24
    • 1970-01-01
    相关资源
    最近更新 更多