【问题标题】:Routing not finding my web api路由找不到我的 web api
【发布时间】:2024-01-19 23:01:01
【问题描述】:

我正在尝试调用我的 web api。

这是 api 控制器:

public class CustomerController : ApiController
{
    [HttpGet]
    [Route("Customer/Get/{CompanyRef}")]
    public IEnumerable<Services.Customer> Get(Guid CompanyRef)
    {
       return customerRepository.Get(CompanyRef);
    }
}

这是我的客户 (c#desktop)

using (HttpClient httpClient = new HttpClient())
{
    Uri uri = new Uri("myuri");
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = await httpClient.GetAsync(uri + route + "?CompanyRef=" + new Guid());
    response.EnsureSuccessStatusCode();
 }

uri 调用转换为:

http://myuri/api/Customer/Get?CompanyRef=00000000-0000-0000-0000-000000000000

我得到的错误是“未找到”?

【问题讨论】:

  • “api”是在哪里定义的?
  • 没有看到您的 webapi 配置,uri 似乎是:myuri/api/Customer/Get/00000000-0000-0000-0000-000000000000
  • @BigDaddy 嗨,我已经添加了类名/路径。它是一个 MVC5 网络应用程序。你是这个意思吗?
  • 您需要确保您的 Web API 路由以“/api”为前缀。否则,您的 MVC 调用将失败。
  • 应该试一试:)

标签: c# httpclient asp.net-web-api2 asp.net-web-api-routing


【解决方案1】:

当谈到 OP 的代码和问题时,公认的答案实际上是完全错误的。那是 ASP.net WEB API v1.x 的路由方式,OP 在他的评论中说使用属性时它是没用的。

[需要 v2+ 的 Web API] 要使 Attributes 起作用并注册路由,您需要在 WebApiConfig.cs Route(config) 方法中添加以下代码:

config.MapHttpAttributeRoutes();

这将解析您所有的 [RoutePrefix("..")][Route("..")] 并创建您的 API 路由。最佳实践是使用 [RoutePrefix("..")] 定义 API 的一般路径以到达您的控制器,然后使用 [Route("..")] 和 http 动词属性(例如 [HttpGet])映射您的不同方法。

【讨论】:

    【解决方案2】:

    您的 Web api 必须在您的 WebApiConfig.cs 文件中包含以下内容:

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

    从您得到的分支看来,您在分支中没有输入参数作为可选参数。我将正常值从 id 更改为 CompanyRef,但我认为 id 可能也可以。

    【讨论】:

    • 没有区别。除了。我认为使用 [Route] 标签的全部目的是避免 webapiconfig?
    • 如果您使用的是 web api 控制器类对象,您的代码中必须有 webapiconfig 部分。
    • 好的,感谢您的确认。我确实在我的 api 配置文件中有它,但它没有任何区别
    • 我的发布肯定有问题。重新启动 IIS 并重新发布,现在它可以工作了。谢谢
    • 我发现如果我改变一些重要的东西,我必须杀死本地主机中的任何东西。它有记忆,但通常不是我想要它记住的。