我理解这个错误是什么和典型的原因,但在这种情况下,我不确定它为什么会被抛出。
这是完整的错误消息:
System.ArgumentException:参数字典包含非可空类型'System.Int32'的参数'Id'的空条目,用于方法'System.Threading.Tasks.Task`1 [System.String] AppUninstalled(Int32)'in' Storefront.Controllers.ShopifyWebhooksController”。可选参数必须是引用类型,可空类型,或者声明为可选参数。参数名称:参数
对我的应用程序调用的URL是:/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调用url,其id明确命名为:/storefront/wh/AppUninstalled?id=88564
但是得到了同样的错误。
可能是编码中的东西,MVC无法将id转换为int吗?
更新2
这是有效的,但它没有解释为什么上述不起作用。
将MVC中的操作方法更改为:public async Task<string> AppUninstalled(string strId)
将Shopify回拨URL更改为:/storefront/wh/AppUninstalled?strId=88564
我怀疑,因为id
在MapRoute
中被声明为可选项,所以你应该声明你的行为:
public async Task<string> AppUninstalled(int? id)
并检查id
是否有值,如果没有则采取行动。
你能尝试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
});