.NET反向代理组件YARP的简单使用
Posted dotNET跨平台
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET反向代理组件YARP的简单使用相关的知识,希望对你有一定的参考价值。
简介
Yarp 是微软团队开发的一个反向代理组件, 除了常规的 http 和 https 转换通讯,它最大的特点是可定制化,很容易根据特定场景开发出需要的定制代理通道。YARP是基于.Net架构的一个库,其提供了核心代理功能,而又因为 .Net Core 是跨平台的,所以可以应用在 windows 于 linux 上;
什么是反向代理
反向代理服务器是代理服务器中的一种,它是在Web服务器之前实现的,并将客户端请求定向到特定的后端服务器。通常,反向代理有助于提高Web服务器的安全性和性能,并防止过载。
实现方法
新建项目:YARPDemo
<ItemGroup>
<PackageReference Include="Yarp.ReverseProxy" Version="1.0.0" />
</ItemGroup>
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace YARPDemo
public class Startup
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
_configuration = configuration;
public void ConfigureServices(IServiceCollection services)
services.AddReverseProxy()
.LoadFromConfig(_configuration.GetSection("ReverseProxy"));
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseEndpoints(endpoints =>
endpoints.MapReverseProxy();
);
appsettings.json
"ReverseProxy":
"Routes":
"route2":
"ClusterId": "cluster_product",
"Match":
"Path": "/api/*all"
,
"Transforms": [
]
,
"Clusters":
"cluster_product":
"Destinations":
"first_destination":
"Address": "http://localhost:5000"
,
"two_destination":
"Address": "http://localhost:5000"
新建Api项目:SwaggerAPI
WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SwaggerAPI.Controllers
[ApiController]
[Route("/api/weatherForecasts")]
public class WeatherForecastController : ControllerBase
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
_logger = logger;
[HttpPost("create")]
public IActionResult Create([FromBody] CreatCommand command)
return Ok("ok" + command.Name);
public class CreatCommand
public string Name get; set;
运行效果:
访问接口:
API
http://localhost:5000/api/weatherForecasts/create
网关代理:
http://localhost:5001/api/weatherForecasts/create
以上是关于.NET反向代理组件YARP的简单使用的主要内容,如果未能解决你的问题,请参考以下文章
YARP(Yet Another Reverse Proxy)是使用 .NET 构建的高度可定制的反向代理