【问题标题】:How to check if POST form data is empty?如何检查 POST 表单数据是否为空?
【发布时间】:2016-07-15 02:31:49
【问题描述】:

我正在.NET 上使用 Nancy 编写一个 CRUD Web api。在尝试进行一些服务器端验证时,我无法阻止在数据库中写入空值的表单。

这是我的控制器/模块:

 public dynamic NEW_POST(dynamic parameters)
        {
            //Binds model to form
            var post = this.Bind<Post>();
            if (post.Title.Length == 0 && post.Content.Length == 0)
            {
                return HttpStatusCode.BadRequest;
            }

            else
            {
                _post.Create(post);
                return Response.AsRedirect("/");
            }

        }

我还尝试检查模型是否 == null。

空值仍然通过控制器并进入数据库。 任何提示将不胜感激,谢谢

【问题讨论】:

    标签: c# asp.net-mvc http nancy


    【解决方案1】:

    这就是我通常会这样做并检查posted 的数据是否为空(就像你说的那样?)。例如:

    public class CustomerModule : NancyModule
    {
        public CustomerModule()
        {
            this.Post["api/customers"] = args => this.AddCustomer();
        }
    
        private Negotiator AddCustomer()
        {
            var customer = this.Bind<Customer>();
    
            if (customer == null)
            {
                return this.Negotiate.WithStatusCode(HttpStatusCode.BadRequest);
            }
    
            return this.Negotiate.WithStatusCode(HttpStatusCode.Created);
        }
    }
    
    public class Customer
    {
        public string Forename { get; set; }
    
        public string Surname { get; set; }
    }
    

    当我在本地启动应用程序时,这是一种享受。如需完整源代码,您可以查看here

    【讨论】:

      【解决方案2】:

      这是检查它的常用方法:

      if (string.IsNullOrWhiteSpace(Request.Form["name"]))
      

      帖子数据包含在 Form 集合中。

      【讨论】:

        猜你喜欢
        • 2015-03-28
        • 2012-11-25
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2017-02-20
        • 1970-01-01
        相关资源
        最近更新 更多