Search code examples
asp.net.netasp.net-core.net-6.0

Request.Query is always empty


I'm working on updating an old ASP .NET MVC project to .NET Core 6. In the old project, I was accessing the request parameter "BATRequestID" through the Request object.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AffectedHardwareAdd()
{
    int? batID = int.Parse(Request["BATRequestID"]);
}

From what I have gathered online, the equivalent line in .NET Core 6 would be

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AffectedHardwareAdd()
{
    int? batID = int.Parse(Request.Query["BATRequestID"].ToString());
}

but everytime the Query parameter is empty. I have also tried adding IHttpContextAccessor to my controller (with builder.Services.AddHttpContextAccessor(); added in Program.cs) but the Query on the request parameter is also empty.

I know I can reformat the post method to take the ID directly, but this syntax is used throughout the program and I would not like to have to change most of my backend if possible.

I've checked to make sure the request is the same in both the old and new project, so I believe it is something on the back end side, such as something missing in services or app.run


Solution

  • If you use the routing method of /controller/action/params, then you put the passed value in Request.RouteValues["id"]: enter image description here

    enter image description here

    The Key value of RouteValues is the parameter name of the default route you set in Program.cs:

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

    If you want to use Request.Query to get parameters, then you need to pass the parameters as a QueryString, ie /controller/action?paramName=xxx: enter image description here

    enter image description here

    For more detail, you can refer to this document: URL matching.