WebAPI 路由默认为 Guid.NewGuid()
本文关键字:NewGuid Guid 路由 默认 WebAPI | 更新日期: 2023-09-27 18:31:12
如果路由配置中未提供相同的 Guid,我正在尝试将 id 生成为新 Guid,但它始终生成相同的 NewGuid。这是我的代码:
config.Routes.MapHttpRoute(
name: "myroute",
routeTemplate: "api/my/route/{userID}",
defaults: new { controller = "my", userID = Guid.NewGuid() }
);
以下是操作方法:
public string Post([FromBody]string value, Guid userID)
{
return "Message Received for User: " + userID.ToString();
}
无论我调用该方法多少次,我都会收到相同的响应,直到除非我重新生成代码。
"Message Received for User: f90b2d6c-29f0-44a0-ba4d-aa72ac25d520"
有人可以指导我这里发生了什么以及如何实现所需的功能吗?
您可以将参数定义为可选参数。
config.Routes.MapHttpRoute(
name: "myroute",
routeTemplate: "api/my/route/{userID}",
defaults: new { controller = "my", userID = RouteParameter.Optional }
);
然后在操作中分配一个值(如果未给出)。
public string Post([FromBody]string value, Guid? userID)
{
userID = userID ?? Guid.NewGuid();
return "Message Received for User: " + userID.ToString();
}
好的...通过添加另一个 post 方法解决了这种情况,这里是最终代码:
config.Routes.MapHttpRoute(
name: "myroute",
routeTemplate: "api/my/route/{userID}",
defaults: new { controller = "my", userID = RouteParameter.Optional }
);
public string Post([FromBody]string value, Guid userID)
{
return "Message Received for User: " + userID.ToString();
}
public string Post([FromBody]string value)
{
Guid userID = Guid.NewGuid();
return "Message Received for User: " + userID.ToString();
}