同一Web API应用程序上的两个控制器

时间:2016-11-22 18:01:48

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

我正在尝试向现有的Web API添加一个控制器。控制器就像

public class TDataController : ApiController
{        
   [HttpGet]
   public HttpResponseMessage Getdetails(string ROOM, DateTime DOB_GT, DateTime DOB_LT, string STATUS_TYPE)
   { 
     // Code for the controller
   }
}

这是我试图在同一个应用程序中添加的控制器

public class TDataSubDateController : ApiController
{
   [HttpGet]
   public HttpResponseMessage Getdetails(string ROOM, string STATUS_TYPE, DateTime? SUBDATE_GT = null, DateTime? SUBDATE_LT = null)
   {
     //Code for the controller
   }
}

当我试图调用第二个控制器时

http://localhost:33823/api/TDataSubDate?ROOM=xxx&STATUS_TYPE=xxx&SUBDATE_GT=xxxx&SUBDATE_LT=xxxx

但它会引发HTTP 404 Page Not Found错误。我是否必须在WebConfig.cs中创建不同的路由。 RouteConfig.cs目前看起来像

     public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

1 个答案:

答案 0 :(得分:2)

如果您使用的是网络API 2,则可以使用属性路由。有关详细信息,请访问https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

以下是单控制器和多个操作的示例

[RoutePrefix("api/tdata")]
public class TDataController : ApiController
{        
    [HttpGet]
    [Route("{ROOM}/preview")]
    public IHttpActionResult Getdetails(string ROOM, [FromUri]DateTime DOB_GT, [FromUri]DateTime DOB_LT, [FromUri]string STATUS_TYPE)
    { 
        return Ok(string.Format("Room {0} Preview", ROOM));
    }

    [HttpGet]
    [Route("{ROOM}/details")]
    public IHttpActionResult Getdetails(string ROOM, [FromUri]string STATUS_TYPE, [FromUri]DateTime? SUBDATE_GT = null, [FromUri]DateTime? SUBDATE_LT = null)
    {
        return Ok(string.Format("Room {0} Details", ROOM));
    }
}

或者进入一个单独的控制器

[RoutePrefix("api/tdatasubdate")]
public class TDataSubDateController : ApiController
{
    [HttpGet]
    public IHttpActionResult Getdetails([FromUri]string ROOM, [FromUri]string STATUS_TYPE, [FromUri]DateTime? SUBDATE_GT = null, [FromUri]DateTime? SUBDATE_LT = null)
    {
        return Ok(string.Format("Room {0} Details", ROOM));
    }
}

以下是webapiconfig.cs的样子

public static class WebApiConfig
{
    /// <summary>
    /// configure global routes
    /// </summary>
    /// <param name="config"></param>
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

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