MVC- How to get parameter value from get request which has parameter names including dot characters
Asked Answered
P

4

29

In MVC, I know we can get parameters from a get request like this:

Request:

http://www.example.com/method?param1=good&param2=bad

And in controller

public ActionResult method(string param1, string param2)
{
   ....
}

But in my situation an external website sends me a get request like:

http://www.example.com/method?param.1=good&param.2=bad

And in controller when i try to meet this request like as follow:

public ActionResult method(string param.1, string param.2)
{
   ....
}

I get build errors because of dot in variable name. How can i get these parameters ? Unfortunately i can not ask them to change parameter names.

Pinter answered 17/2, 2014 at 15:12 Comment(0)
T
45

Use the following code:

    public ActionResult method()
    {
        string param1 = this.Request.QueryString["param.1"];
        string param2 = this.Request.QueryString["param.2"];

        ...
    }
Theoretician answered 17/2, 2014 at 15:23 Comment(0)
C
19

This will probably be your best bet:

/// <summary>
/// <paramref name="param.1"/>
/// </summary>
public void Test1()
{
    var value = HttpContext.Request.Params.Get("param.1");
}

Get the parameter from HttpContext.Request.Params rather than putting it as an explicit parameter

Cat answered 17/2, 2014 at 15:49 Comment(3)
i tried this too and this also works. i dont know which one is better method but i accepted ssimeonov's answer since he replied earlier.Pinter
The Params property will let you access form and cookie info as well. See linkAttack
Request('param.1') will let you access form and cookie info too.Bairam
T
2
The Framework
  public void ProcessRequest(HttpContext context)
  {
     string param1 = context.Request.Params["param.1"];

Replace by .net core 3.1

ControllerBase 
  ...
    [ApiController]
    [Route("[controller]")]
   ...

     string param1 = HttpContext.Request.Query["param.1"];
     string param2 = HttpContext.Request.Query["param.2"];
Thine answered 23/6, 2020 at 21:13 Comment(0)
H
0

Maybe a late response but can be useful.

For a request like nooaa posted :

http://www.example.com/method?param1=good&param2=bad

The solution of ssimeonov will work :

   string param1 = this.Request.QueryString["param1"];
   string param2 = this.Request.QueryString["param2"];

Will return the parameters. But, if the URL is called by an API with parameters, request.QueryString can return null (or empty).

In any case the best solution will be

   var value = HttpContext.Request.Params.Get("param1");

As James Haug has proposed.

Humdrum answered 25/4 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.