ASP.NET 核心怪异 URL 解析。单个查询字符串参数

ASP.NET Core weird URL parsing. Single query string parameter

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

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

这是我的配置class:

    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

这是一个错误吗?

出现该行为是因为您将值“myvalue”作为 returned ViewResult 的第一个参数传递,即视图名称参数:

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

如果您将 return 语句更改为:

return View();

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