我在构建查询字符串时遇到了一些问题。我有一个模型:
[HttpGet]
public partial class Task
{
public System.Guid UniqueID { get; set; }
public string Description { get; set; }
public decimal Priority { get; set; }
public long TaskTypeId { get; set; }
public TaskStatus TaskStatus { get; set; }
public string GroupWorkspaceUrl { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> Deadline { get; set; }
public Nullable<int> PlannedHours { get; set; }
{...}
}
我在 Controller 中有 2 个 Action :
[HttpGet]
public virtual ActionResult TaskCreate(string schemaType)
{
var model = new Task();
model.Accept(_taskService.ReaderVisitor, schemaType)
{...}
}
[HttpGet]
public virtual ActionResult TaskCreateWithModel(string schemaType, Task model)
{
SetDefaultValues(model);
model.Accept(_taskService.ReaderVisitor, schemaType);
{...}
}
我想从其他 C# WinForms 解决方案构建一个查询字符串,该解决方案调用 Controller 中的第二个操作(public virtual ActionResult TaskCreateWithModel(string schemaType,Task model))但我不知道如何发送任务模型在查询字符串中?我试图调用此查询字符串:http://localhost:82/Task/TaskCreate?schemaType=default&Description=someDesciption
但总是调用第一个操作。如何使用任务模型构建查询字符串?
最佳答案
使用 HTTP GET 操作创建新任务资源是非常不寻常的。 GET 应该是幂等的(即,如果您多次发出相同的请求,效果与您发出一次相同 - 没有副作用)
此外,使用 GET 进行创建操作可能会使您容易遭受跨站点请求伪造 (CSRF),因为 ASP.Net MVC 防伪保护仅适用于 POST。
创建操作通常是 HTTP POST(或可能是 PUT),其中任务对象的数据包含在请求正文中而不是查询字符串中。此外,使用查询字符串会限制您可以拥有的数据量(URL 限制为 2000 个字符?)。
如果您使用 HTTP POST 方法,那么 ASP.Net MVC 的自动模型绑定(bind)将从请求主体创建正确类型的对象,因此您将能够执行如下操作
[HttpPost]
public virtual ActionResult TaskCreateWithModel(string schemaType, Task model)
如您所愿,但使用 POST 而不是 GET,并且不使用查询字符串。此处对 MVC 中的模型绑定(bind)有很好的描述
http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx
关于c# - Action 的 MVC4 查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962253/