我正在尝试执行以下操作.
使用默认模型绑定器从查询字符串值绑定对象.
如果失败,我会尝试从cookie值绑定对象.
但是我在这个对象上使用dataannotations,我遇到了以下问题.
这是我到目前为止所拥有的.
public class MyCarBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var myCar = base.BindModel(controllerContext, bindingContext);
if (!bindingContext.ModelState.IsValid)
{
myCar = MyCar.LoadFromCookie();
// Not sure what to do to revalidate
}
return myCar;
}
}
Run Code Online (Sandbox Code Playgroud)
任何有关如何正确执行此操作的帮助将不胜感激.
我的应用程序在ro-RO文化设置下运行,在web.config全球化部分中配置.如果我发出一个POST请求
POST /myapp/index
date=03-12-2010&value=something
Run Code Online (Sandbox Code Playgroud)
模型绑定将此映射到正确的日期值"2010年12月3日",因为ro-RO文化的默认日期时间格式为dd-MM-yyyy.如果我将请求方法更改为GET传递相同的数据,我的操作中的日期值将变为"2010年3月12日"(MM-dd-yyyy日期时间格式)
GET /myapp/index?date=03-12-2010&value=something
$.getJSON('/Home/Index', $('form').serialize(), function(d) {
// ...
});
$.post('/Home/Index', $('form').serialize(), function(d) {
// ...
}, 'json');
Run Code Online (Sandbox Code Playgroud)
所以在这种情况下,"getJson"和"post"必须返回相同的结果,但由于日期时间差异,我得到不同的结果.
如何为GET请求启用相同的解析格式?
我知道我可以使用更通用的格式,例如yyyy-MM-dd作为日期,但我只是好奇为什么会发生这种情况?
我有一个Asp.net MVC应用程序,目前使用默认模型绑定器和具有复杂参数的URL,如下所示:
example.com/Controller/Action?a=hello&b=world&c=1&d=2&e=3 (注意问号)
不同的URL使用内置的模型绑定器自动映射到Action Method参数.我想继续使用标准模型绑定器,但我需要摆脱查询字符串.我们希望将这些网址放在CDN之后,该CDN不支持因查询字符串(Amazon Cloud front)而异的资源,因此我们需要从我们的网址中删除问号并执行类似这样的操作
example.com/Controller/Action/a=hello&b=world&c=1&d=2&e=3 (无问号)
这些网址只能通过AJAX使用,所以我对使用户或SEO友好不感兴趣.我想删除问号并保持我的所有代码完全相同.问题是,我不确定如何继续使用MVC模型绑定器并放弃它将是一项很多工作.
我不想使用复杂的路线来映射我的对象,就像这个问题一样,相反,我打算使用一条简单的路线,如下所示
routes.MapRoute(
"NoQueryString", // Route name
"NoQueryString/{action}/{query}", // 'query' = querystring without the ?
new {
controller = "NoQueryString",
action = "Index",
query = "" } // want to parse with model binder - By NOT ROUTE
);
Run Code Online (Sandbox Code Playgroud)
选项1(首选):OnActionExecuting 我计划在控制器动作使用我的控制器中的OnActionExecuting方法执行之前,使用上面路由中的catchall"query"值将旧的查询字符串注入默认模型绑定器.但是,我有点不确定我是否可以添加问号. 我可以这样做吗?你会如何建议修改网址?
选项2:自定义模型Binder 我也可以创建某种自定义模型绑定器,它只是告诉默认模型绑定器将"查询"值视为查询字符串. 你更喜欢这种方法吗?你能指点我一个相关的例子吗?
我有点担心这是一个边缘情况,并且在我开始尝试实现选项1或选项2并偶然发现不可预见的错误之前会喜欢一些输入.
我有一个自定义的ModelBinder(MVC3),由于某种原因没有被解雇.以下是相关的代码:
视图
@model WebApp.Models.InfoModel
@using Html.BeginForm()
{
@Html.EditorFor(m => m.Truck)
}
Run Code Online (Sandbox Code Playgroud)
EditorTemplate
@model WebApp.Models.TruckModel
@Html.EditorFor(m => m.CabSize)
Run Code Online (Sandbox Code Playgroud)
ModelBinder的
public class TruckModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
Global.asax中
protected void Application_Start()
{
...
ModelBinders.Binders.Add(typeof(TruckModel), new TruckModelBinder());
...
}
Run Code Online (Sandbox Code Playgroud)
InfoModel
public class InfoModel
{
public VehicleModel Vehicle { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
VehicleModel
public class VehicleModel
{
public string Color { get; set; }
public int NumberOfWheels { get; set; }
} …Run Code Online (Sandbox Code Playgroud) 假设我有两个类派生于另一个类:
动物和狗
public class Animal
{
public String Name { get; set; }
}
public class Dog : Animal
{
public Boolean HasSpots { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我将动物传递给索引视图
public ActionResult Index()
{
return View(new Dog() {Name = "Dog"});
}
Run Code Online (Sandbox Code Playgroud)
索引 - 我将传入的Animal转换为带有Dog的编辑器模板.
@model MvcApplication1.Models.Animal
@using (Html.BeginForm("About", "Home", FormMethod.Post, null))
{
@Html.EditorFor(x => x, "Dog", "Animal")
<input type="submit" value="Begin" />
}
Run Code Online (Sandbox Code Playgroud)
这样可以正常工作,但是当我尝试在我的控制器中显式转换回Dog时,我将它发布到About它将不会投射.我想象一下,我将不得不创建一个自定义模型绑定器,但我不知道如何做到这一点.或者,如果我完全错过了一些东西.没有包括接口的任何方式.
(使用它作为一个小测试示例,我的实际类更复杂一些)
我正在尝试将JSON对象发布到Web Api URL,并且它不绑定到模型.
这似乎是同样的问题:ASP.Net Web Api在POST上没有绑定模型
我尝试了他们所做的一切,但仍然无效.您可能注意到的一个区别是我没有使用DataContract属性,但我不相信它们应该被要求,并且在我尝试它们时没有任何区别.
public class MyModel
{
public int Id { get; set; }
}
Public class MyController : ApiController
{
public int Save(MyModel myModel)
{
// myModel is always null
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)

我的MVC代码中有一个服务器端对象,如下所示:
class Person
{
public long Id { get; set; }
public string Name { get; set; }
public IList<Friend> Friends { get; set; }
}
class Friend
{
public long Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
从jQuery客户端,我正在发出ajax请求并发送以下数据(为了可读性而引入了换行符):
var personId = $(...
var personName = $(...
var friends = []; // array of associative arrays
for (var i = 0; i < _friends.length; i++) // _friends is is a global array object and …Run Code Online (Sandbox Code Playgroud) 对于 MVC4,通过 将ViewModel用于填充视图的视图发送回控制器的最佳实践方法是POST什么?
我有这个控制器,我不知道为什么name参数为null
public class DeviceController : ApiController
{
[HttpPost]
public void Select([FromBody]string name)
{
//problem: name is always null
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的路线图:
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}"
);
appBuilder.UseWebApi(config);
}
Run Code Online (Sandbox Code Playgroud)
这是我的要求:
POST http://localhost:9000/api/device/Select HTTP/1.2
User-Agent: Fiddler
Host: localhost:9000
Content-Length: 16
Content-Type: application/json
{'name':'hello'}
Run Code Online (Sandbox Code Playgroud)
我还尝试将正文更改为纯字符串:hello。
POST http://localhost:9000/api/device/Select HTTP/1.2
User-Agent: Fiddler
Host: localhost:9000
Content-Length: 5
Content-Type: application/json
hello
Run Code Online (Sandbox Code Playgroud)
该请求返回204,这没问题,但是该参数从不映射到发布值。
*我使用的是自托管的owin服务。
我想确定用户是否正在尝试在Asp.NET MVC中进行过度发布攻击。
如何确定某人是否正在向控制器发送特殊值(例如,通过Fiddler)?
请注意下面的“绑定”属性
Run Code Online (Sandbox Code Playgroud)[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "LastName, FirstMidName, EnrollmentDate")]Student student) { try { if (ModelState.IsValid) { db.Students.Add(student); db.SaveChanges(); return RedirectToAction("Index"); } } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(student); }Bind属性是一种防止在创建方案中过度发布的方法。例如,假设Student实体包含一个您不想设置此网页的Secret属性。
Run Code Online (Sandbox Code Playgroud)public class Student { public int ID { get; …
model-binding ×10
asp.net-mvc ×7
c# ×5
casting ×1
data-binding ×1
jquery ×1
json ×1
model ×1
modelbinders ×1
owin ×1
post ×1
security ×1