配置Web API路由配置

时间:2017-04-15 15:16:32

标签: asp.net-web-api

我的控制器中有一个api动作,如下所示。

    [RoutePrefix("api/export")]
    public class ExportController : ApiController
    {
        [HttpPost]
        public HttpResponseMessage Report([FromBody]ReportInput input, string reportType)
        {
        }
    }

我已经为我的路由配置添加了一个配置。

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{reportType}",
            defaults : new {reportType = RouteParameter.Optional}
        );

但我无法在下面调用我的API网址。我应该做哪种配置?

localhost:50773/api/export/report/InsuranceHandlingFiles

1 个答案:

答案 0 :(得分:0)

您似乎已使用atttribute routing(以[RoutePrefix]的形式)。你可以完全切换到它。您只需执行此操作,而不是当前的路由配置:

config.MapHttpAttributeRoutes();

然后,要映射/api/export/report/InsuranceHandlingFiles等网址,请在控制器方法中添加其他[Route]属性:

[RoutePrefix("api/export")]
public class ExportController : ApiController
{
    [HttpPost, Route("report/{reportType}")]
    //         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    //                  add this
    public HttpResponseMessage Report([FromBody]ReportInput input, string reportType)
    {
        …
    }
}

如果您希望reportType是可选的,请为string reportType参数指定默认值,并且(如果这不足够),添加第二条路线; e.g:

[HttpPost, Route("report/{reportType}"), Route("report")]
public HttpResponseMessage Report([FromBody]ReportInput input, string reportType = null)
{
    …
}
相关问题