URL已指定ID,但仍在获取参数字典中包含参数“ Id”错误的空条目

时间:2019-03-06 07:16:40

标签: c# asp.net-web-api asp.net-mvc-5 shopify asp.net-web-api-routing

我了解此错误的含义和典型原因,但是在这种情况下,我不确定为什么会抛出该错误。

这是完整的错误消息:

  

System.ArgumentException:参数字典包含空值   非空类型为'System.Int32'的参数'Id'的条目   方法'System.Threading.Tasks.Task`1 [System.String]   AppUninstalled(Int32)'   “ Storefront.Controllers.ShopifyWebhooksController”。可选的   参数必须是引用类型,可为空的类型,或声明为   可选参数。参数名称:参数

针对我的应用程序调用的网址是:/storefront/wh/AppUninstalled/88564。因此它会将Id作为int传递。

这是路线定义:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Storefront_default",
        "Storefront/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

这是被称为的动作签名:public async Task<string> AppUninstalled(int id)

现在,当我在本地或使用Postman在登台服务器上对此进行测试时,不会出现此错误。但是当Shopify调用它时,我确实得到了错误。而且我可以通过生成的Elmah错误来验证,所调用的URL就像我上面发布的一样,带有尾随的ID值。

更新:1

我也尝试用shopify调用带有显式命名为/storefront/wh/AppUninstalled?id=88564的ID的url,但遇到相同的错误。

是否可能是MVC无法将id转换为int的编码形式?

更新2

这行得通,但不能解释为什么上面的行不通。

在MVC中将操作方法​​更改为:public async Task<string> AppUninstalled(string strId)

将Shopify回调网址更改为:/storefront/wh/AppUninstalled?strId=88564

2 个答案:

答案 0 :(得分:0)

我怀疑由于idMapRoute中被声明为可选,因此您应该这样声明操作:

public async Task<string> AppUninstalled(int? id)

然后检查id是否具有值,如果没有,则采取措施。

答案 1 :(得分:0)

您可以尝试使用RouteParameter.OptionalMapHttpRoute而不是UrlParameter.OptionalMapRoute

   routes.MapHttpRoute( // <-- this
                name: "Storefront_default",
                routeTemplate: "Storefront/{controller}/{action}/{id}",
                defaults: new {action ="Index", id = RouteParameter.Optional // <-- this 
});