【问题标题】:ASP.NET Core weird URL parsing. Single query string parameterASP.NET Core 奇怪的 URL 解析。单个查询字符串参数
【发布时间】:2023-04-03 18:00:01
【问题描述】:

我想将一个字符串参数传递给一个动作。在HomeController 中创建了一个具有以下签名的方法:

[HttpGet]
public IActionResult TestView([FromQuery] string test)
{
    return View(test);
}

这是我的配置类:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

当我去 https://localhost:5001/Home/TestView 它工作正常 当我添加查询字符串 ?test=myvalue 时,它​​无法找到视图。它尝试使用奇怪的路径来定位视图。

    InvalidOperationException: The view 'myvalue' was not found. The following locations were searched:
    /Views/Home/myvalue.cshtml
    /Views/Shared/myvalue.cshtml

这是一个错误吗?

【问题讨论】:

  • Startup.cs 中的中间件是什么?
  • @Jacek 我发布了整个 Startup.cs。虽然,我没碰过。它来自默认的 MVC 模板

标签: c# asp.net-core asp.net-core-mvc url-routing


【解决方案1】:

发生这种行为是因为您将值“myvalue”作为返回的 ViewResult 的第一个参数传递,即 viewname 参数:

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.viewresult.viewname?view=aspnetcore-5.0

如果您将退货声明更改为:

return View();

那么您将不会传递视图名称参数,然后它将搜索名为 TestView 的视图。

【讨论】:

  • 别担心,兄弟。如果您希望在浏览器中看到“myvalue”,请将返回类型更改为字符串,然后可以返回测试,完全绕过视图。或者,您可以改为将值绑定到视图。只是取决于你想做什么。
  • @SergеуIsupov 第一个参数是视图名称,如果你想给视图传递一些东西,把它传递给第二个参数。因此,在您的情况下,您可以编写 View("TestView", test) - 视图模型的类型为 string ,视图应该知道正确使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多