我了解此错误的含义和典型原因,但是在这种情况下,我不确定为什么会抛出该错误。
这是完整的错误消息:
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
答案 0 :(得分:0)
我怀疑由于id
在MapRoute
中被声明为可选,因此您应该这样声明操作:
public async Task<string> AppUninstalled(int? id)
然后检查id
是否具有值,如果没有,则采取措施。
答案 1 :(得分:0)
您可以尝试使用RouteParameter.Optional
和MapHttpRoute
而不是UrlParameter.Optional
和MapRoute
routes.MapHttpRoute( // <-- this
name: "Storefront_default",
routeTemplate: "Storefront/{controller}/{action}/{id}",
defaults: new {action ="Index", id = RouteParameter.Optional // <-- this
});