ASP. NET Core Extension Library Http General Extension Library

  • 2021-11-29 06:41:53
  • OfStack

Directory 1. Turn on server-side request buffering 2. Request header delivery 3. Record of request header log 4. Extension method on Http message 5. Extension methods on HttpClient

This article describes the extension of the Xfrogcn. AspNetCore. Extensions extension library to other Http-related features that address common requirements, including request buffering, request header delivery, request header log range, and extension methods for HttpClient, HttpRequestMessage, and HttpResponseMessage.

1. Turn on server-side request buffering

The request body in ASP. NET Core cannot be read more than once, since the framework has already read the request body in MVC, if you read it again in the controller, an exception will be thrown, as shown in the following example:


    [ApiController]
    [Route("[controller]")]
    public class TestController : ControllerBase
    {
 
        public TestController()
        {

        }

        [HttpPost]
        public async Task<WeatherForecast> Save([FromBody]WeatherForecast enttiy)
        {
            using (StreamReader reader = new StreamReader(Request.Body))
            {
                Request.Body.Position = 0;
                string response = await reader.ReadToEndAsync();
            }
            return enttiy;
        }
    }

The statement Request. Body. Position fires an exception when the/test interface is requested through Post:


System.NotSupportedException: Specified method is not supported.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.set_Position(Int64 value)

Of course, requests may not be processed as in the example in practice, but in business requirements, it is true that the request body may be read multiple times.

You can solve the problem of reading the request body multiple times by turning on request buffering. The Xfrogcn. AspNetCore. Extensions extension library provides EnableBufferingAttribute feature for turning on request buffering, which you can use for controllers or Action methods.

For the above example, simply add the EnableBuffering feature to the Save method:


    [HttpPost]
    [EnableBuffering]
    public async Task<WeatherForecast> Save([FromBody]WeatherForecast enttiy)
    {
        ....
    }

2. Request header delivery

Under the microservice architecture, we usually use the request header to realize the link tracking of the request and the association between the log and the request. For example, through x-request-id, the relevant log of a request in all services can be directly viewed in the log system.

By intercepting the HttpClient request pipeline, the extension library can automatically transfer the specified request header. By default, the extension library will automatically pass the request header starting with "x-". If you need to pass other request headers, you can add them through TrackingHeaders in the configuration.


    IServiceCollection services = new ServiceCollection()
        .AddExtensions(null, config =>
        {
            //  Automatically pass to my- Request header for prefix 
            config.TrackingHeaders.Add("my-*");
        });

3. Record of request header log

. NET Core log framework, the concept of log range is realized. Through log range, the log system can record the information of current context. For example, in ASP. NET Core MVC, the log range contains the relevant information of ActionContext, so the relevant information of Action can be automatically recorded in all logs of one request.

The extended library can add the configured request header to the requested log range. For example, under the default configuration, the extended library will add x-request-id to the requested log range, so all logs in a single 1 request can automatically carry x-request-id information, so as to realize cross-service log association. To include additional request headers, you can set it through HttpHeaders in the configuration:


    IServiceCollection services = new ServiceCollection()
        .AddExtensions(null, config =>
        {
            //  Will my-id Request header included in log range 
            config.HttpHeaders.Add("my-id");
        });

Note: The default console logs and file logs do not save information about the log range. You can use the json format for console logs or file logs, which will save the data in the log range.


    IServiceCollection services = new ServiceCollection()
        .AddExtensions(null, config =>
        {
            config.ConsoleJsonLog = true;
        });

4. Extension methods on Http messages

The extension library provides GetObjectAsync and WriteObjectAsync extension methods on HttpRequestMessage, which is convenient for reading and writing request messages. GetObjectAsync and WriteObjectAsync extension methods are provided on HttpResponseMessage to facilitate the reading and writing of reply messages. These methods are all in json format.

Example:


    public class WeatherForecast
    {
        public DateTime Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

        public string Summary { get; set; }
    }

    static async Task Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection()
            .AddExtensions(null, config =>
            {
            });

        IServiceProvider serviceProvider = services.BuildServiceProvider();

        IHttpClientFactory factory = serviceProvider.GetRequiredService<IHttpClientFactory>();
        HttpClient client = factory.CreateClient();

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5000/test");
        
        //  Write request object 
        await request.WriteObjectAsync(new WeatherForecast()
        {
            Date = DateTime.Now
        });
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        //  Read the request object 
        var entity = await request.GetObjectAsync<WeatherForecast>();

        HttpResponseMessage response = await client.SendAsync(request);

        //  Read the reply object 
        entity = await response.GetObjectAsync<WeatherForecast>();

        Console.ReadLine();
    }

5. Extension methods on HttpClient

In order to use HttpClient more conveniently and quickly, the extension library adds several extension methods to HttpClient:

PostAsync < TResponse > Sends an object to the server and gets a response of the specified type PostAsync: Send the object to the server and get the reply string GetAsync < TResponse > Send an Get request and get an TResponse type reply GetAsync: Send an Get request and get an String type reply SubmitFormAsync < TResponse > Submit form data to the server and get an TResponse type response SubmitFormAsync: Submit form data to the server and get an String-type response UploadFileAsync < TResponse > : Last local file UploadStreamAsync < TResponse > Upload streaming data to the server

Refer to documentation GitHub Gitee for a detailed description of these extension methods

Xfrogcn. AspNetCore. Extensions Address: GitHub Gitee

The above is the ASP. NET Core Extension Library of Http General Extension Library of the details of the use of the details, more about ASP. NET Core Extension Library of Http General Extension Library of information please pay attention to other related articles on this site!


Related articles: