使用.Net Core 3.1的POST请求和Power Automate的HTTP请求

时间:2020-10-29 06:36:20

标签: c# json.net httprequest asp.net-core-3.1 power-automate

我遇到问题是使用.Net Core 3.1 MVC在Power Automate的发布请求中发送参数。我创建了一个具有参数Name和Age的简单应用程序,然后一个View有一个按钮,当您单击它时,它会发送对Power Automate HTTP Request提供的POST请求的回复,并且我将收到一封包含Name和Age的电子邮件。设置为人物模型。但是,每次我收到电子邮件时,其名称和年龄都是空的。下面提供一些详细信息是我的源代码:

Index.cshtml

<a asp-controller="Test" asp-action="SendNameAge" class="btn btn-success" >Json Trigger</a>

Success.cshtml

<p>success request</p>

Failed.cshtml

<p>Failed request</p>

Model.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace WebApplication.Model
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

TestController.cs

using Microsoft.AspNetCore.Mvc;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using WebApplication.Model;
using WebApplication.Utility;

namespace WebApplication.Controllers
{
    public class TestController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Success()
        {
            return View();
        }

        public IActionResult Failed()
        {
            return View();
        }

        public async Task<IActionResult> SendNameAge()
        {
            using (var client = new HttpClient())
            {
                Person person = new Person
                {
                    Name = "Juan Dela Cruz",
                    Age = 32
                };

                client.BaseAddress = new Uri(SD.ApiUri);
                var response = await client.PostAsJsonAsync(SD.ApiUri, person);

                if (response.IsSuccessStatusCode)
                {
                    return RedirectToAction(nameof(Success), Json(response));
                }
                else
                {
                    return RedirectToAction(nameof(Failed), Json(response));
                }
            }
        }
    }
}

这是单击按钮时收到的电子邮件,也是我应该收到的带有参数的电子邮件,但我只是使用邮递员进行测试。

来自.Net Core的电子邮件 Email receive from .Net Core

使用邮递员发送电子邮件 Email receive using Postman

1 个答案:

答案 0 :(得分:0)

尝试将您的Person模型转换为JSON,然后仅使用简单的PostAsync

Person person = new Person
{
    Name = "Juan Dela Cruz",
    Age = 32
};
var personJSON = JsonConvert.SerializeObject(person);
var buffer = System.Text.Encoding.UTF8.GetBytes(personJSON);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var response = await client.PostAsync(SD.ApiUri, byteContent);