WebAPI URL未按预期进行路由



我在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;
}
...

不出所料,urlhttps://localhost:44382/API/Socket返回异常:

<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]是可选的,但它使程序员更清楚地了解数据的来源。

最新更新