【问题标题】:Request["key"] is not working in C# web application (ASP.NET Core)Request["key"] 在 C# Web 应用程序 (ASP.NET Core) 中不起作用
【发布时间】:2020-04-29 08:36:02
【问题描述】:

我正在尝试从视图中获取参数并将其传递给控制器​​:

 [HttpPost]
 public string GetWord()
 {
     string word = Request["word"];
     return word;
 }

但是我遇到了一个错误

使用 [] 构造的索引不能用于 Http 请求表达式

我查看了文档,但不知道为什么它不起作用。我应该怎么做才能解决这个问题?

【问题讨论】:

  • “word”是查询参数、正文的一部分还是来自请求的其他部分?
  • 我的 Index.cshtml 中有它:
  • 我有:@using (Html.BeginForm("GetWord", "Home"))
  • 这是哪个版本的 .net? .net 核心或 .net 框架

标签: c# web request http-post


【解决方案1】:

您可以使用更具体的属性来获取值,而不是 Request["word"],这取决于“word”键的位置:

  1. 在查询字符串中 -> Request.QueryString["word"];
  2. 在服务器变量中 -> Request.ServerVariables["word"];
  3. 在参数中 -> Request.Params["word"];
  4. 在表格中 -> Request.Form["word"];
  5. 在 Cookie 中 -> Request.Cookies["word"];
  6. 在标题中 -> Request.Headers["word"];

在您的情况下,您可以使用第 4 个:Request.Form["word"],但请确保 <input> 控件包含在 BeginFrom 标记中。

【讨论】:

    【解决方案2】:

    尝试将参数绑定到表单

     [HttpPost]
     public string GetWord([FromForm]string word)
     {
         var postedWord = word;
         return postedWord;
     }
    

    随着您的表单变得越来越复杂,您可能希望创建一个类并将提交的表单绑定到该类

     public string GetWord([FromForm]MyFormModel formData) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 2019-06-25
      • 2018-11-30
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多