路由属性在Web API 2中不起作用

时间:2016-12-19 22:05:15

标签: asp.net-web-api2

我的API控制器上有两个GET方法。当我尝试调用我使用Route属性修饰的GetByCompanyId方法时,请求将被路由到GetById方法。以下是相关的代码文件。

global.ascx.cs

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

webApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.EnableCors();

        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

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

    }
}

route.config

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

CompanyFunctionsController.cs

public IHttpActionResult GetById(int id)
{
    var companyFunction = this._service.GetByKey(new object[] { id });

    if (companyFunction != null)
    {
        var companyFunctionDto = Mapper.Map<CompanyFunctionDto>(companyFunction);

        return Ok(companyFunctionDto);
    }

    return NotFound();
}

[Route("CompanyFunctions/GetByCompanyId", Name = "GetByCompanyId")]
[HttpGet]
public IEnumerable<CompanyFunctionDto> GetByCompanyId(int id)
{
    var collection = this._service.GetAll().ToList().Where(x => x.CompanyId == id);

    IEnumerable<CompanyFunctionDto> collectCompanyFunctionDtos = Mapper.Map<IEnumerable<CompanyFunctionDto>>(collection);

    return collectCompanyFunctionDtos;
}

我的HTTP请求: http://localhost:1317/api/CompanyFunctions/GetByCompanyId?id=1

2 个答案:

答案 0 :(得分:2)

Web API 2支持一种称为属性路由的新型路由。顾名思义,属性路由使用属性来定义路由。通过属性路由,您可以更好地控制Web API中的URI 您可以在Web Api中使用属性路由来解决您的问题。您的控制器操作应该是这样的,

    [Route("CompanyFunctions/GetByCompanyId/{companyId}"]
 public IEnumerable<CompanyFunctionDto> GetByCompanyId(int companyId)
 {
    var collection = this._service.GetAll().ToList().Where(x => x.CompanyId == companyId);

    IEnumerable<CompanyFunctionDto> collectCompanyFunctionDtos = Mapper.Map<IEnumerable<CompanyFunctionDto>>(collection);

    return collectCompanyFunctionDtos;
 }

,您的HTTP请求为http://localhost:1317/CompanyFunctions/GetByCompanyId/1

答案 1 :(得分:1)

如果您希望路径以http://localhost:1317/api/CompanyFunctions/GetByCompanyId?id=1开头,例如api,那么您必须在路径属性中使用您希望它转到的字符串[Route("api/CompanyFunctions/GetByCompanyId", Name = "GetByCompanyId")]

[RoutePrefix("api/CompanyFunctions")]

否则它只会根据http动词匹配(在这种情况下为Get)。

或者,您也可以使用[Route("GetByCompanyId", Name = "GetByCompanyId")]属性修饰web api控制器,并将Route属性更改为-1 % 7