c# - ASP.NET MVC : How does a controller distingush between parameters in the URL and sent by POST

标签 c# asp.net-mvc model-binding

我想更好地了解 Controller 方法如何知道何时应该从发布数据或 url 中检索它接收的参数。

举个例子:

URL: /ModelController/Method/itemID 
// Where itemID is the id (int) of the item in the database
POST: objectOrArray: {JSON Object/Array}

Controller 看起来像这样:

[HttpPost]
public ActionResult InputResources(int? id, Object objectOrArray)

现在,该方法以某种方式足够智能,可以查找第一个参数,id。 , 在站点 URL 和 ObjectHTTPPost .

虽然这行得通,但我不知道为什么,结果我有时会遇到不可预测和不稳定的行为。例如,我似乎发现(尽管我不是 100% 确定)删除 ?来自 int? id使 Controller 方法立即假设它应该在 HTTPPost 中查找 id而不是网址。

所以我想澄清以下几点:

到底是什么告诉方法去哪里寻找数据? (预示方法的 [HttpPost] 属性?)

命名约定是否起作用? (例如删除 ? 或不使用 id 作为变量名?)

变量的放置顺序是否有影响? (即将 Object 放在 id 之前)

我知道我可以或多或少地通过反复试验弄清楚其中的一些东西,但我想要一个合格的解释,而不是继续基于观察的假设工作。

谢谢

乔波

最佳答案

查看 Global.asax 中的默认路由:

routes.MapRoute(
    "Default",                                            
    "{controller}/{action}/{id}",                     
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

MVC 将尝试做的第一件事是将您的方法参数映射到 POST 中的值。如果找不到匹配项,它将通过其他可能性级联,包括路由值。

这是模型 Binder 使用的顺序:

  1. Previously bound action parameters, when the action is a child action
  2. Form fields (Request.Form)
  3. The property values in the JSON Request body (Request.InputStream), but only when the request is an AJAX request
  4. Route data (RouteData.Values)
  5. Querystring parameters (Request.QueryString)
  6. Posted files (Request.Files)

您看到您描述的行为的原因是因为 POST 数据出现在路由值之前。似乎 MVC 无法将可为空的 int 绑定(bind)到 POST 值,因此它跳过它并继续前进,直到它到达 RouteData 映射,此时它找到匹配项并获取值从路线。当您使参数不可为 null 时,它突然能够将其绑定(bind)到 POST 值,它比 RouteData 具有更高的优先级,所以它确实如此。

来源:http://msdn.microsoft.com/en-us/magazine/hh781022.aspx

关于c# - ASP.NET MVC : How does a controller distingush between parameters in the URL and sent by POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16232736/

相关文章:

c# - MVC EditorFor model binding for multiple edit forms on a page

c# - 在 WebAPI 中绑定(bind)抽象操作参数

c# - 如何使用 XSLT 将 Richtext 图像从标准 WPF RichTextBox 转换为 HTML?

c# - 当前不会命中断点。尚未在 Silverlight 应用程序中为此文档加载任何符号

c# - 正则表达式选择单词的一部分

asp.net - ASP.NET MVC 中的分页

html - 当值为 bool 类型时,无法使用 viewbag 设置隐藏字段的值。

c# - MVC 自定义身份验证、授权和角色实现

c# - C# 和 T-SQL 自带哪些统计函数?

c# - 对象列表的回发为空