c# - ASP.NET Core 奇怪的 URL 解析。单个查询字符串参数
问题描述
我想将一个字符串参数传递给一个动作。AcreatedHomeController
具有以下签名的方法:
[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
那是一个错误吗?
解决方案
发生该行为是因为您将值“myvalue”作为返回的 ViewResult 的第一个参数传递,即 viewname 参数:
如果您将退货声明更改为:
return View();
然后您将不会传递视图名称参数,然后它将搜索名为 TestView 的视图。
推荐阅读
- javascript - 将回调的结果按顺序沿链向下传递到外部回调
- sql - 为什么ROWNUM <=,左外连接和子查询的这种组合有时会给出null
- c# - 如何在 C# 中的多个 XML 文件中搜索 XElement 属性值?
- php - 使用 foreach 循环添加 DateTime 间隔
- ios - SwiftUI 中的 CALayer 等效项
- asterisk - “请选择 PBX 的默认区域设置”页面在 FreePBX 中经常出现
- reactjs - 生产模式风格的组件缩小导致类型错误
- python - Flask 返回重复列表
- r - R:找出每组直线上有多少点
- javascript - 在将 js 脚本添加到 html 后,在 react.js App 中它不起作用