"当前上下文中不存在 'Request' 名称"

6

编辑:我现在已将Request更改为Context.Request,现在收到了另一个错误信息,与此帖子的标题不同:Cannot apply indexing with [] to an expression of type 'HttpRequest'

所以我正在尝试介绍ASP.Net,并按照这里提供的在线教程进行操作:https://www.w3schools.com/asp/webpages_forms.asp(“显示图像”部分)。我正在尝试以MVC风格的布局来实现它。 结构的起始模板是运行dotnet new -t web时生成的模板的修改版本。

在我的Pictures.cshtml文件中,我有以下代码:

@{
    ViewData["Title"] = "Pictures";

    var imagePath="";
    if (Request["Choice"] != null) 
    {
       imagePath="images/" + Request["Choice"];
    }
}

<h2>Pictures</h2>

<form method="post" action="">
    I want to see:
    <select name="Choice">
    <option value="Photo1.jpg">Photo 1</option>
    <option value="Photo2.jpg">Photo 2</option>
    <option value="Photo3.jpg">Photo 3</option>
    </select>
    <input type="submit" value="Submit" />
    @if (imagePath != "")
    {
        <p>
        <img src="@imagePath" alt="Sample" />
        </p>
    }
</form>

这是从MainController.cs中调用的:

using Microsoft.AspNetCore.Mvc;

namespace WebApp.Controllers
{
    public class MainController : Controller
    {
        public IActionResult Pictures()
        {
             return View();
        }
    }
}

还有一个_ViewStart.cshtml文件引用了_Layout.cshtml。

运行时,我被重定向到错误页面,并在终端上收到错误消息The name 'Request' does not exist in the current context

请问有人能指导我缺少什么或者我做错了什么吗?为什么这个教程示例在我的项目中无法工作?

谢谢 :)


您没有名为“Choice”的元素。请尝试将您的选择重命名为“Choice”。 - AGuyCalledGerald
你使用的是哪个MVC版本?它是否识别Request对象?尝试在.Net Core中使用Context.Request。 - AGuyCalledGerald
这是 .Net Core,我今天才意识到它们是两个不同的框架!我尝试了 Context.Request,现在我得到了“无法将 [] 索引应用于类型为 'HttpRequest' 的表达式”的错误。 - jamessct
又出现新错误了!“运算符'!='对类型为'StringValues'和'<null>'的操作数不明确”。 - jamessct
我真的不确定它是否有效,但请尝试!String.IsNullOrEmpty(Context.Request.Form["Choice"]) - AGuyCalledGerald
显示剩余2条评论
2个回答

6

我在Core 2.1中遇到了同样的错误。我发现如果将其放在ViewDataStyles部分,很难调试(或者有些怪异)。否则,对于特定参数,它应该像这样工作:

@Context.Request.Query["Choice"]

针对你的代码,我建议先请求一次值并将其赋值给一个变量,然后查看该变量是否为空。接下来,从你的变量创建路径:

var choice = @Context.Request.Query["Choice"];
var imagePath="";
if (!String.IsNullOrEmpty(choice)){
   imagePath="images/" + choice;
}

作为额外的奖励,您还可以通过以下方式获取包含所有名称和值的完整查询字符串(如果您想解析它或其他什么):

@Context.Request.QueryString

4
我在ASP Core 5.0中使用了这个代码:
ViewContext.HttpContext.Request.Query["Choice"]

JS中的示例:

if (getParameterByName("error") != null) {
   window.location.href = "@Url.Action("Login", "Home" , new { error = ViewContext.HttpContext.Request.Query["Choice"] })";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接