简体   繁体   中英

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

I want to pass a string parameter to an action. Acreated a method in the HomeController with the following signature:

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

This is my configuration 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?}");
            });
        }
    }

When I go to https://localhost:5001/Home/TestView it works ok When I add a query string?test=myvalue it fails to find the view. It tries to locate the view using weird paths.

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

Is that a bug?

The behavior is occurring because you passed the value "myvalue" as the first parameter of your returned ViewResult, which is the viewname parameter:

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

If you change your return statement to:

return View();

Then you won't be passing a view name parameter and it will then search for a view named TestView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM