C# 添加其他参数时无法连接到ASP.NET web api
我正在尝试理解WebAPI2(VisualStudio中的MVC项目) 方法是C# 添加其他参数时无法连接到ASP.NET web api,c#,asp.net-web-api2,asp.net-web-api-routing,C#,Asp.net Web Api2,Asp.net Web Api Routing,我正在尝试理解WebAPI2(VisualStudio中的MVC项目) 方法是 [HttpPost] public string Post(int id, string e, bool o) ///code removed 使用Postman,我可以使用Post和路径http://localhost:62093/api/Demo/5。这将起作用并返回预期值 现在我想添加更多的参数,这就是问题所在 我已将我的方法更新为 [HttpPost] public string
[HttpPost]
public string Post(int id, string e, bool o)
///code removed
使用Postman,我可以使用Post
和路径http://localhost:62093/api/Demo/5
。这将起作用并返回预期值
现在我想添加更多的参数,这就是问题所在
我已将我的方法更新为
[HttpPost]
public string Post(int id, string e, bool o)
现在,当我尝试(再次)使用Post
和路径http://localhost:62093/api/Demo/5
我明白了
“消息”:“请求的资源不支持http方法‘POST’。”
然后我尝试更改URL,因此当我使用Post
和新路径http://localhost:62093/api/Demo/5/a/false
我看到一个HTML文件响应
找不到该资源
这已经在Stackoverflow上提到过,据我所知,URL是“不正确的”
认为这可能是我更新我的路线的问题
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{s}/{o}",
defaults: new { id = RouteParameter.Optional, s = RouteParameter.Optional, o = RouteParameter.Optional }
);
但同样的问题依然存在。我不确定我做错了什么。这是一个路由问题。您尚未正确配置路由 首先,让我们更新
WebApiConfig.cs
文件
现在配置好后,我建议使用属性路由
最后,我建议您继续阅读,以便更好地了解如何正确路由到API控制器特别感谢您提供了指向属性路由的链接。
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
public class DemoController : ApiController {
[HttpPost]
[Route("api/Demo/{id:int}/{e}/{o:bool}")] //Matches POST api/Demo/5/a/false
public IHttpActionResult Post(int id, string e, bool o) {
return Ok();
}
}