我在建立查询字串时遇到问题。我有一个模型:

[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; }
       {...}
    }


我在控制器中有2个动作:

[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解决方案中构建一个查询字符串,该解决方案在控制器中调用第二个动作(公共虚拟ActionResult TaskCreateWithModel(string schemaType,Task model)),但是我不知道如何在查询字符串中发送Task模型?我尝试调用此查询字符串:http://localhost:82/Task/TaskCreate?schemaType=default&Description=someDesciption,但始终会调用第一个操作。如何使用任务模型构建查询字符串?

最佳答案

使用HTTP GET操作创建新任务资源是非常不寻常的。 GET应该是幂等的(即,如果多次发出相同的请求,则效果与一次发出的效果相同-无副作用)

此外,由于ASP.Net MVC防伪保护仅与POST一起使用,因此还使用GET进行创建操作会使您易于跨站点请求伪造(CSRF)。

创建操作通常是HTTP POST(或者可能是PUT),其中任务对象的数据包含在请求正文中,而不是查询字符串中。另外,使用查询字符串会限制您可以拥有的数据量(URL最多2000个字符?)。

如果使用HTTP POST方法,则ASP.Net MVC的自动模型绑定将从请求正文中创建正确的类型化对象,因此您将可以执行以下操作

[HttpPost]
public virtual ActionResult TaskCreateWithModel(string schemaType, Task model)


根据需要,但使用POST而不是GET,并且不使用查询字符串。这里有一个关于MVC中的模型绑定的很好的描述

http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx

关于c# - MVC4查询字符串到一个 Action ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18962253/

10-12 00:27
查看更多