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

问题描述 投票:1回答:2

我理解这个错误是什么和典型的原因,但在这种情况下,我不确定它为什么会被抛出。

这是完整的错误消息:

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

c# asp.net-web-api asp.net-mvc-5 shopify asp.net-web-api-routing
2个回答
0
投票

我怀疑,因为idMapRoute中被声明为可选项,所以你应该声明你的行为:

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

并检查id是否有值,如果没有则采取行动。


0
投票

你能尝试RouteParameter.OptionalMapHttpRoute而不是UrlParameter.OptionalMapRoute

   routes.MapHttpRoute( // <-- this
                name: "Storefront_default",
                routeTemplate: "Storefront/{controller}/{action}/{id}",
                defaults: new {action ="Index", id = RouteParameter.Optional // <-- this 
});
© www.soinside.com 2019 - 2024. All rights reserved.