Using. Net core to realize reverse proxy Middleware

Time:2020-5-21

Recently, when migrating the rest API of some projects to. Net core, nginx was used as the reverse proxy at the beginning, and the part that has completed the switch was cut into the system, as shown in the following figure:

Due to the code reconstruction in the migration process, frequent tests are required to ensure that the introduced problems can be found in time. As a result, we need to configure a routing map of nginx for each part of the migration to ensure that the migration function can cut into the system test.

After a period of time, it is found that it is difficult to configure nginx frequently, and it is easy to configure it wrongly. So I want to put the function of the reverse agent in the. Net core program, and realize the following functions:

  1. Rest requests are sent directly to the. Net core program
  2. If the request is implemented in the. Net core program, the request is executed and returned
  3. If it is not implemented, it requests the data of the old interface and returns the result.

Form a structure as follows:

Try it out. It’s easy to implement this function in. Net core. Add a middleware of reverse proxy:


public class ReverseProxy
  {
    static HttpClient _http = new HttpClient();

    public static async Task Invoke(HttpContext context)
    {
      var url = context.Request.Path.ToUriComponent();
      var uri = new Uri("http://localhost:8080/api" + url);

      var request  = CopyRequest(context, uri);
      var remoteRsp = await _http.SendAsync(request);
      var rsp    = context.Response;

      foreach (var header in remoteRsp.Headers)
      {
        rsp.Headers.Add(header.Key, header.Value.ToArray());
      }

      rsp.ContentType  = remoteRsp.Content.Headers.ContentType?.ToString();
      rsp.ContentLength = remoteRsp.Content.Headers.ContentLength;

      await remoteRsp.Content.CopyToAsync(rsp.Body);
    }


    static HttpRequestMessage CopyRequest(HttpContext context, Uri targetUri)
    {
      var req = context.Request;
      var requestMessage = new HttpRequestMessage()
      {
        Method   = new HttpMethod(req.Method),
        Content  = new StreamContent(req.Body),
        RequestUri = targetUri,
      };

      foreach (var header in req.Headers)
      {
        requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
      }

      requestMessage.Headers.Host = targetUri.Host;

      return requestMessage;
    }
  }

It is also relatively simple to use. Put it at the back of the configure function, and directly use run to reverse proxy all the requests that are not implemented by the system.


  app.Run(Middleware.ReverseProxy.Invoke);

Here I am just a relatively simple implementation, about 20 or 30 lines of code, which is not very perfect. But try it, the basic functions are also available. Interested friends can improve it. This function itself is only a transitional function. If there is any update in the subsequent use process, it will be put up.

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.

Recommended Today

Mysql database: application of function

String truncation #First character from left Left (field name, 1) #From there, take a few Substring (field name, 1,1) STR function #Connection string concat(s1,s2,s3,……,sn); concat_WS(‘sep’,s1,s2,s3,……,sn); #Remove all spaces at the beginning and end of a string TRIM(str) #Remove the characters in the leading. TRIM(leading ‘x’,str) #Returns the string STR in the reverse order of the […]