1

I am migrating project from Net 4.6.2 into Net Core 2. What is the replacement for Request in MVC Net Core 2? How do I replace this line below? string rawId = Request["ProductID"];

In Net Core 2, I am receiving

Error:

Cannot apply indexing with [] to an expression of type 'HttpRequest'    HPE.Kruta.Web.Core

https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest?view=netframework-4.7.2

Code Example:

protected void Page_Load(object sender, EventArgs e)  
{  
    string rawId = Request["ProductID"];  
    int productId;  
    if (!String.IsNullOrEmpty(rawId) && int.TryParse(rawId, out productId))  
    {  
        using (ShoppingCartActions usersShoppingCart = new ShoppingCar
Dai
  • 141,631
  • 28
  • 261
  • 374

1 Answers1

0

ASP.NET WebForms is not directly convertable to ASP.NET MVC and ASP.NET Core because the "web form" paradigm does not translate well to the controller+action+model+binding system used in ASP.NET MVC. I recommend you read these other QAs first:

The old HttpRequest object combined both QueryString and Form values together, but that's a bad design and now you need to explictly check one or the other (or both) so you know exactly where the value is coming from.

However, if you have a querystring value, you should make that a controller action parameter instead of using the Request object. You can use strongly-typed values (like Int32 instead of String so you don't need to perform validation and conversion yourself. Like so:

public async Task<IActionResult> GetShoppingCart( [FromQuery] Int32 productId )
{
    ShoppingCart cart = await this.db.GetShoppingCartAsync( productId );

    ShoppingCartViewModel vm = new ShoppingCartViewModel()
    {
        Cart = cart
    };

    return this.View( model: vm );
}

However, if you would still prefer to access raw querystring or posted form values as their original string values, then do it like so.

Note that Form and Query are no-longer NameValueCollection objects but more strongly-typed classes that correctly expose "single key, multiple values" data more correctly. So do this to get the "ProductId" value like before:

String rawId = this.Request.Form["ProductId"].FirstOrDefault() ?? this.Request.Query["ProductId"].FirstOrDefault();

Because each Form entry is StringValues instead of String you need to always use FirstOrDefault() to get a single string value (don't use SingleOrDefault() because it will throw an exception if 2 or more values are present for the same key). Secondarily, the ?? operator will make the program check the querystring if the named value is not present in the posted Form values first.

The Form and Query collections return StringValues.Empty instead of null if the specified key is not found in either collection so you won't risk a NullReferenceException by using the FirstOrDefault() extension method if the key isn't present in the dictionary.

Dai
  • 141,631
  • 28
  • 261
  • 374