gpt4 book ai didi

c# - 如何在 Controller 级别使用 Route

转载 作者:行者123 更新时间:2023-11-30 16:45:49 24 4
gpt4 key购买 nike

我在这里尝试使用 [Route] 属性调用 WebApi Controller

为什么 http://localhost:57997/Hello/Jan/1 不是配置的路由while http://localhost:57997/Hello/Jan 获取数据

using a = System.Web.Http;

[a.Route("Hello/Jan")]
public IEnumerable<Department> GetDepartmets()
{
var x = pro.GetDept();
return x.ToList();
}

[a.Route("Hello/Jan/{id?}")]
public HttpResponseMessage GetDepartmets(int id)
{
if (id != null)
{
var x = pro.GetDeptById(id);
return Request.CreateResponse(HttpStatusCode.OK, x);
}
else
return Request.CreateResponse(HttpStatusCode.NotFound);

}

最佳答案

这是一个最小的完整可验证示例,它基于您关于 Controller 使用属性路由的外观的原始帖子。

using a = System.Web.Http;

[a.RoutePrefix("Hello/Jan")] //RoutePrefix used to group common route on controller
public MyController : ApiController {

//...other code removed for brevity. ie: pro

//GET Hello/Jan
[a.HttpGet]
[a.Route("")]
public IHttpActionResult GetDepartmets() {
var departments = pro.GetDept().ToList();
return Ok(departments);
}

//GET Hello/Jan/1
[a.HttpGet]
[a.Route("{id:int}")] //Already have a default route. No need to make this optional
public IHttpActionResult GetDepartmet(int id) {
var department = pro.GetDeptById(id);
if (department != null) {
return Ok(department);
}

return NotFound();
}
}

注意:确保在WebApiConfig

中启用属性路由
//enable attribute routing
config.MapHttpAttributeRoutes();

//...before other convention-based routes.

关于c# - 如何在 Controller 级别使用 Route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41441205/

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