gpt4 book ai didi

asp.net-web-api2 - 路由属性在 Web API 2 中不起作用

转载 作者:行者123 更新时间:2023-12-01 08:29:34 25 4
gpt4 key购买 nike

我的 API Controller 上有两个 GET 方法。当我尝试调用用路由属性修饰的 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 }
);

}
}

路由配置

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

最佳答案

如果你想要一个以 api 开头的路由,比如 http://localhost:1317/api/CompanyFunctions/GetByCompanyId?id=1 那么你必须使用您希望它转到的路由属性中的字符串 api

[Route("api/CompanyFunctions/GetByCompanyId", Name = "GetByCompanyId")]

否则它只会根据 http 动词(在本例中为 Get)进行匹配。

或者,您也可以使用 [RoutePrefix("api/CompanyFunctions")] 属性装饰 Web api Controller ,并将您的 Route 属性更改为 [Route("GetByCompanyId", Name = "GetByCompanyId")]

关于asp.net-web-api2 - 路由属性在 Web API 2 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41231775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com