gpt4 book ai didi

asp.net Web Api 路由不起作用

转载 作者:行者123 更新时间:2023-12-04 00:30:44 29 4
gpt4 key购买 nike

这是我的路由配置:

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

而且,这是我的 Controller :
public class ProductsController : ApiController
{
[AcceptVerbs("Get")]
public object GetProducts()
{
// return all products...
}

[AcceptVerbs("Get")]
public object Product(string name)
{
// return the Product with the given name...
}
}

当我尝试时 api/Products/GetProducts/ ,它的工作原理。 api/Products/Product?name=test也有效,但 api/Products/Product/test不起作用。我做错了什么?

更新:

这是我尝试时得到的结果 api/Products/Product/test :
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:42676/api/Products/Product/test'.",
"MessageDetail": "No action was found on the controller 'Products' that matches the request."
}

最佳答案

这是因为您的路由设置及其默认值。你有两个选择。

1) 通过更改路由设置以匹配 Product() 参数以匹配 URI。

config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{name}", // removed id and used name
defaults: new { name = RouteParameter.Optional }
);

2)另一种推荐的方法是使用正确的方法签名属性。
public object Product([FromUri(Name = "id")]string name){
// return the Product with the given name
}

这是因为该方法需要一个参数 id 请求时
api/Products/Product/test 而不是寻找 姓名 参数。

关于asp.net Web Api 路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21760762/

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