简体   繁体   English

路由找不到我的Web API

[英]Routing not finding my web api

I am trying trying to call my web api. 我正在尝试调用我的Web API。

This is the api controller: 这是api控制器:

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

This is my client (c#desktop) 这是我的客户(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();
 }

the uri call translates to: uri呼叫转换为:

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

the error I get is 'not found'? 我得到的错误是“未找到”?

Your web api must have the following in your WebApiConfig.cs file: 您的Web API必须在WebApiConfig.cs文件中包含以下内容:

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

It appears from the branching you are getting that you don't have the input parameter in the branch as an optional parameter. 从您得到的分支看来,您在分支中没有输入参数作为可选参数。 I changed the normal value from id to CompanyRef, but I think id would likely work as well. 我将正常值从id更改为CompanyRef,但我认为id也可能会起作用。

The accepted answer is actually completely in the wrong when it comes to OP's code and question. 当涉及到OP的代码和问题时,公认的答案实际上是完全错误的。 That is ASP.net WEB API v1.x way of doing the routing and OP is right in his comment that it is useless when using attributes. 那就是ASP.net WEB API v1.x的路由方式,OP在他的评论中正确地指出,使用属性时它是无用的。

[v2+ of Web API required] For Attributes to work and the routes to be registered, you need to add the following code in your WebApiConfig.cs Route(config) method: [需要Web API v2 +]为了使属性起作用并注册路由,您需要在WebApiConfig.cs Route(config)方法中添加以下代码:

config.MapHttpAttributeRoutes();

That will parse all your [RoutePrefix("..")] and [Route("..")] and create your API's routing. 这将解析所有[RoutePrefix("..")][Route("..")]并创建API的路由。 It is a best practice to use [RoutePrefix("..")] to define the general path of the API in order to reach your controller & then map your different methods using the [Route("..")] & http verb attribute such as [HttpGet] . 最佳实践是使用[RoutePrefix("..")]定义API的常规路径,以便到达您的控制器,然后使用[Route("..")]和http动词映射不同的方法属性,例如[HttpGet]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM