WebAPI URL 未按预期路由

WebAPI URL is not routing as expected

我在我的 WebAPI 控制器中定义了以下两种方法:

public class SocketController : ApiController
{
    [HttpGet]
    [Route("api/socket")]
    public List<SocketInfo> GetAllSockets()
    {
        throw new Exception("Not Implemented; Use API/Socket/{ConfigId} to request a specific socket.");
    }

    [HttpGet]
    [Route("api/socket/{Id}")]
    public SocketInfo GetSocket(string configId)
    {
        SocketInfo si = new SocketInfo();
        si.ConfigId = configId;
        si.Password = "****************";
        si.SystemName = "_SystemName";
        si.Type = Definitions.SocketType.DTS;
        si.Subtype = Definitions.SocketSubtype.PUT;

        return si;
    }
    ...

正如预期的那样,url https://localhost:44382/API/Socket returns 异常:

<Error>
   <Message>An error has occurred.</Message>
   <ExceptionMessage>Not Implemented; Use API/Socket/{ConfigId} to request a specific socket. 
   </ExceptionMessage>
   <ExceptionType>System.Exception</ExceptionType>
   <StackTrace>
   ...

好的,让我们尝试通过 Id 检索特定的套接字:https://localhost:44382/API/Socket/ab24def6

但由于某种原因,这没有路由。这是我得到的:

<Error>
   <Message>No HTTP resource was found that matches the request URI 
           'https://localhost:44382/API/Socket/ab24def6'.
   </Message>
   <MessageDetail>No action was found on the controller 'Socket' that matches the request. 
   </MessageDetail>
</Error>

有谁知道为什么这不是路由?

试试这个:

[HttpGet, Route("api/socket/{configId}")]
public SocketInfo GetSocket([FromRoute] string configId)
{
    // ...
}

问题是您的参数名称与路由参数名称不匹配。 [FromRoute] 在这种情况下是可选的,但它使程序员更清楚数据的来源。