ASP.NET Example of core MVC getting the parameters of the request

Time:2020-8-14

preface

An HTTP request is a standard IO operation. The request is I, which is the input; the responsive o is the output. Any web development framework is actually doing these two things

  • Accept the request and parse to get the parameters
  • Render according to the parameters and output the response content

So let’s learn a framework, and I think the most important thing is to know how to get parameters from requests. HTTP requests carry parameters mainly in the following places:

  • URL
  • Header
  • Body

Let’s take a look ASP.NET How does the core get parameters from these locations.

Get parameters by URL

The most commonly used method of HTTP is to pass parameters through URL. Here is a brief introduction to the URL related knowledge. A URL is mainly divided into four parts to http://localhost For example: 5000 / fromurl / test? Name = mjzhou & age = 10

http:// agreement
localhost:5000 Host address
/fromurl/test PATH
name=mjzhou&age=10 QueryString

We usually use path and querystring to pass parameters. Create a new MVC project and a new controller named fromurlcontroller. Demonstrate how to get parameters from URL through several actions.

Get parameters through querysting

Request.Query object


  // /fromurl/test?name=mjzhou
  public IActionResult Test()
  {
   var name = Request.Query["name"];
   return Content(name);
  }

Request.Query The object contains the list of key value pairs of the querystring in this request, so you can easily get the parameters carried on the querystring through it.

Automatic parameter binding


  // /fromurl/test?name=mjzhou
  public IActionResult Test1(string name)
  {
   return Content(name);
  }

If the name of the type parameter of the action is consistent with the key of the querystring, the MVC framework will automatically bind the value of the parameter for us, and it is not necessary to obtain it manually.


  public IActionResult Test2([FromQuery(Name = "id")]string bh)
  {
   return Content(bh);
  }

If the name of the parameter binding does not match the key of the querystring, you can use the fromqueryattribute to force the name of the bound key.

Get parameters through path

Request.Path object


//  /fromurl/test3
  public IActionResult Test3()
  {
   var path = Request.Path;
   return Content(path);
  }

Request.Path The object contains the original information of the path of this HTTP request, which can be separated by /, and the desired parameters can be obtained manually.

Automatic parameter binding


//  /fromurl/Test4/mjzhou/1000
  [Route("FromUrl/test4/{name}/{id}")]
  public IActionResult Test4(string name, int id)
  {
   return Content($"{name}/{id}");
  }

The automatic parameter binding of path needs to be implemented in cooperation with routeattribute. Routeattribute mainly specifies a path template. Through this template, you can tell whether the route matches the action. The other is to tell the parameter binding, how to parse the path and realize parameter binding.


  [Route("FromUrl/test6/{name}/{id}")]
  public IActionResult Test6([FromRoute(Name ="name")]string xm, [FromRoute(Name = "id")]int bh)
  {
   return Content($"{xm}/{bh}");
  }

If the type parameter name of the action is different from the name in the routeattribute template, you can use fromroute to force the name of the resolution.


  [HttpGet("FromUrl/test5/{name}/{id}")]
  public IActionResult Test5(string name, int id)
  {
   return Content($"{name}/{id}");
  }

Attributes such as httpgetattribute and httppostattribute can also complete the effect of routeattribute, and also specify the HTTP method method method accepted by action, which can be said to be the enhanced version of routeattribute.

Get parameters from header

Add a fromheadercontroller to demonstrate how to get parameters from HTTP headers through several actions.

Request.Headers object


  // /FromHeader/test
  public IActionResult Test()
  {
   var myName = Request.Headers["myName"];

   return Content(myName);
  }

Request.Headers Is a dictionary that contains the headers of this request. So we can go through Request.Headers Object to easily get the value of a header.

Automatic parameter binding


  public IActionResult Test1([FromHeader]string myName)
  {
   return Content(myName);
  }

By typing the fromheaderattribute on the type parameter of the action, you can tell the framework to automatically get the parameters from the header.


  public IActionResult Test2([FromHeader(Name = "myName")]string name)
  {
   return Content(name);
  }

If the type parameter of the action is inconsistent with the key value of the header, the key value of the matching header can be forced to be specified through the fromheaderattribute.

Get parameters from body

When we develop, we often submit data through forms, or submit a JavaScript object to the background through Ajax. In essence, these data are submitted back through HTTP bady. Create a new frombodycontroller controller and demonstrate how to obtain the parameters of the body through several actions.

Request.Body object


  public class model1
  {
   public string NAME { get; set; }
  }

  public async Task<IActionResult> Test()
  {
   Request.EnableBuffering();

   string body = "";
   var stream = Request.Body;
   if (stream != null)
   {
    stream.Seek(0, SeekOrigin.Begin);
    using (var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true))
    {
     body = await reader.ReadToEndAsync();
    }
    stream.Seek(0, SeekOrigin.Begin);
   }

   var model = JsonConvert.DeserializeObject<model1>(body);

   return Content(model.NAME);
  }

Request.Body It is a stream that stores the body data of this request. So as long as we read the stream, we can get the submitted data. With the original data, you can convert it into a model through operations such as deserialization, and get parameters more easily. be careful, ASP.NET To read this object, the core must first call Request.EnableBuffering () this method.

Use postman to test:

Parameter auto binding


  public IActionResult Test1([FromBody]model1 model)
  {
   return Content(model.NAME);
  }

Using frombodyattribute, the data of body can be automatically deserialized to form parameter model. However, please note that the content type requested with [frombody] must be application JSON.

Using postman, the following tests were performed:



  public IActionResult Test2([FromForm]model1 model)
  {
   return Content(model.NAME);
  }

Using fromformattribute, the data of body can be automatically deserialized to form the model of parameter. However, please note that the content type requested with [fromform] must be application / x-www-form-urlencoded.

Using postman, the following tests were performed:

summary

ASP.NET The core obtains the request parameters mainly from the URL, headers, body, etc. We can go through Request.Query , Request.Headers , Request.Body To get the data manually. You can also use attributes such as [fromquery], [fromheader], [frombody] to automatically bind parameters.

Well, this is about ASP.NET Core MVC gets the parameters of the request in this article, more related ASP.NET Core MVC get request parameter content, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!