gpt4 book ai didi

c# - 无法在 Asp.NET MVC 中命中 Api 路由

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:01 24 4
gpt4 key购买 nike

我有一个 ASP.NET MVC 应用程序。我正在向这个应用程序添加一些 API。我的一些 API 有效。其他人没有。我遇到的问题是我也不知道。我应该使用什么路线或 b。如果我没有正确注册路线。例如,我有以下 WebApi:

namespace MyProject.Controllers
{
public class ProjectApiController : System.Web.Http.ApiController
{
[ResponseType(typeof(IEnumerable<Product>))]
public IHttpActionResult Get(string search, int max)
{
// Clean up the query
string query = q.Trim().ToLower();

// Get the products
List<Product> products = Product.GetAll();
var results = (from product in products
where product.Name.ToLower().Contains(query)
select new
{
Id = product.Id,
Name = product.Name
}).Take(max);

// Return the results
return Ok(results);
}

[ResponseType(typeof(IEnumerable<Category>))]
public async Task<IHttpActionResult> GetCategories(string search, int max)
{
// Clean up the query
string query = q.Trim().ToLower();

// Get the products
List<Category> products = Category.GetAll();
var results = (from category in categories
where category.Name.ToLower().Contains(query)
select new
{
Id = category.Id,
Name = category.Name
}).Take(max);

// Return the results
return Ok(results);
}
}
}

当我访问 /api/projectApi?search=tes&max=5 时,如果第二种方法被注释掉,我会得到一个我想要的 JSON 数组。如果第二种方法未注释,我会收到一条错误消息,内容如下:

"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nGet on type MyProject.Controllers.ProjectApiController\r\nGetCategories on type MyProject.Controllers.PrjectApiController","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}

理想情况下,我希望能够调用:

/api/projectApi/projects?search=tes&max=5

/api/projectApi/categories?search=tes&max=5

但是,我似乎无法弄清楚该怎么做。我做错了什么?

谢谢!

最佳答案

如果您使用 ASP.NET api 2,您现在还可以使用路由属性来装饰您的方法,例如

[Route("/api/projectApi/products")]
[ResponseType(typeof(IEnumerable<Product>))]
public IHttpActionResult Get(string search, int max)
{ ...
}

[Route("/api/projectApi/categories")]
[ResponseType(typeof(IEnumerable<Category>))]
public async Task<IHttpActionResult> GetCategories(string search, int max)
{ ...
}

参见 http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

关于c# - 无法在 Asp.NET MVC 中命中 Api 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26161863/

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