【发布时间】:2011-10-21 20:28:46
【问题描述】:
在我们将应用程序升级到 MVC3 之前,我有这条路线有效:
routes.MapRoute(
"Versioned API with Controller, ID, subentity",
"api/{version}/{controller}/{id}/{subentity}/",
new { controller = "API", action = "Index" },
new { id = @"\d+", subentity = "serviceitem|accessitem" }
),
我正在尝试通过 POST 到以下网址来访问这条路线:
/api/1.0/items/3/serviceitem
我的控制器方法有这个签名:
[ActionName("Index"), AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateServiceItem(int id)
当我尝试使用此方法时,我收到以下错误:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult CreateServiceItem(Int32)' in 'API.Controllers.ItemsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
在 mvc2 和 mvc3 之间是否有某种语法变化?
编辑:更新信息!
我想我找到了罪魁祸首。我将一些 JSON 数据的数据发布到 URL。我的 JSON 对象恰好如下所示:
{ Id: null, OtherProperty: 'foo' }
MVC3 正在使用我的 JSON 对象中的 ID,而不是 URL 中指定的 ID。此行为是否可配置?
编辑 2:可重现的示例:
我们在应用程序中使用 Ext,所以我的示例是使用 Ext,但我可以重现它,这是在我的 /Views/Home/Index.aspx 中:
Ext.onReady(function() {
var w = new Ext.Window({
title: 'Hi there',
height: 400,
width: 400,
items: [
new Ext.Button({
text: 'Click me',
handler: function() {
var obj = {
Id: null,
Text: 'Hi there'
};
Ext.Ajax.request({
url: '/item/3/serviceitem',
method: 'POST',
jsonData: Ext.util.JSON.encode(obj),
headers: { 'Content-type': 'application/json' },
success: function(result, request) {
console.log(result);
},
failure: function(result, request) {
console.log(result);
}
});
}
})
]
});
w.show();
});
在我的 Global.asax 中,我有以下路线:
routes.MapRoute(
"Test",
"{controller}/{id}/{subentity}",
new { action = "Index" },
new { id = @"\d+", subentity = "serviceitem" }
);
在我的 /Controllers/ItemController 中,我有这个方法:
[ActionName("Index")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateServiceItem(int id)
{
string data;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
data = sr.ReadToEnd();
}
return Json(new
{
DT = DateTime.Now,
Id = id,
PostedData = data
});
}
当我点击按钮时,导致带有指定 JSON 数据的控制器 POST,我得到与上面相同的错误。如果我不发送 JSON 数据,它可以工作(因为 MVC 将使用 URL 部分作为我的方法的参数)。
这是我的复制解决方案的链接:http://www.mediafire.com/?77881176saodnxp
【问题讨论】:
-
基本上我和这个问题有同样的问题:stackoverflow.com/questions/6334818/…
标签: asp.net-mvc-3 asp.net-mvc-routing