我想在View中获取“id”参数,但Context.Request.Query["id"]
会返回空值。
像这样查询: localhost:1000/MyController/Getuser/65190907-1145-7049-9baa-d68d44b1ad06
// Controller
public ActionResult Getuser(Guid id)
{
//HttpContext.Request.Query["id"] also return null
return View();
}
//in startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
答案 0 :(得分:1)
Request.Query
包含请求的查询字符串,即在问号后面的URL部分:...?param1=value1¶m2=value2
。网址localhost:1000/MyController/Getuser/65190907-1145-7049-9baa-d68d44b1ad06
不包含查询字符串。 GUID 65190907-1145-7049-9baa-d68d44b1ad06
只是网址路径的一部分。
如果由于某种原因你想从原始请求访问id参数,而不是通过模型绑定,你有两个选择:
在查询字符串中传递id
并通过HttpContext.Request.Query["id"]
访问它:
在这种情况下,请求网址为http://localhost:1000/MyController/Getuser?id=65190907-1145-7049-9baa-d68d44b1ad06
。不需要改变路线。
第二个选项是从id
中提取Request.Path
:
public IActionResult Getuser(Guid id)
{
var path = HttpContext.Request.Path;
var id2 = Guid.Parse(path.Value.Split('/').Last());
return View();
}
答案 1 :(得分:0)
我想我可以通过ViewContext.ModelState["id"].AttemptedValue