Dapr .NetCore 订阅与发布(下) 电脑版发表于:2021/10/25 13:23 ![](https://img.tnblog.net/arcimg/hb/896fd38e95b346f9a0d98c54b135bb94.jpg) >#Dapr .NetCore 订阅与发布(下) [TOC] 解决关于运行是报错问题 ------------ tn2>我们将为`InvokeMethodServer`API项目做一些修改。 首先添加一些相关依赖 ```xml <ItemGroup> <PackageReference Include="CloudNative.CloudEvents" Version="1.3.80" /> <PackageReference Include="CloudNative.CloudEvents.AspNetCore" Version="1.3.80" /> <PackageReference Include="Dapr.AspNetCore" Version="1.4.0" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> </ItemGroup> ``` tn2>创建`RequestController`控制器,设置`/dapr/subscribe`订阅与发布的配置,这里我们添加一个NewSong方法并且将路径设置为`/playlist/hello`. ```csharp [ApiController] [Route("[controller]")] public class RequestController : ControllerBase { private readonly ILogger<RequestController> _logger; public RequestController(ILogger<RequestController> logger) { _logger = logger; } [HttpGet("/dapr/subscribe")] public ActionResult<IEnumerable<string>> Get() { var topics = new [] {new { pubsubname="pubsub",topic = "songs", route = "playlist/hello"}}; return new OkObjectResult(topics); } [HttpPost("/playlist/hello")] public async Task<IActionResult> NewSong(CloudEvent cloudEvent) { var song = JsonConvert.DeserializeObject<Song>(cloudEvent.Data.ToString()); _logger.LogInformation($"New song request: {song.Artist} – {song.Name}"); return new OkResult(); } } public class Song { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("artist")] public string Artist { get; set; } [JsonProperty("name")] public string Name { get; set; } } ``` tn2>在 Startup 类中,为了帮助进行模型绑定,让我们为 CloudEvents添加一个输入格式化程序 ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddDapr(); services.AddMvc(opts => { opts.InputFormatters.Insert(0, new CloudNative.CloudEvents.CloudEventJsonInputFormatter()); }); } // 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.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` tn2>运行测试 ```bash dapr run --app-id myserer --app-port 5002 --dapr-http-port 3500 -- dotnet run ``` ![](https://img.tnblog.net/arcimg/hb/0717cb5c98b34ac7af855ee1a7dac4b4.png) tn2>dapr cri调用 ```bash dapr publish --publish-app-id myserer --pubsub pubsub --topic songs --data '{"id":17,"name":"dapr_cli_mysongs","artist":"hhh"}' ``` tn2>bash调用 ```bash curl -X POST http://localhost:3500/v1.0/publish/pubsub/songs -H "Content-Type: application/json" -d '{"id":17,"name":"bash_mysongs","artist":"hhh"}' ``` ![](https://img.tnblog.net/arcimg/hb/af8b7212ea734c21b64bbaadfbe626d2.png) ![](https://img.tnblog.net/arcimg/hb/c0fe5244531f498883643e01a23ba269.png) tn2>从其他客户端dapr请求过来的也能响应到。