WebAPI路由默认Guid.NewGuid()

时间:2016-01-19 19:33:01

标签: c# asp.net-web-api

我正在尝试将id作为新的Guid生成,如果路由配置中没有提供相同的ID,但它总是生成相同的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"

有人可以指导我这里发生的事情以及如何实现所需的功能吗?

2 个答案:

答案 0 :(得分:2)

您可以将参数定义为可选参数。

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();
}

答案 1 :(得分:0)

好的...通过添加另一个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();
}