我正在尝试在我的 Azure 数据库帐户上发布一个项目。我编写并发布了一个 ASP.Net Core Web 应用程序到 Azure 帐户,该应用程序实现了 Get、Post、Put 和 Delete 等方法。在我的 Xamarin Forms 项目中,我试图调用 HttpClient PostAsync 方法在 Azure 数据库中创建(发布)一条记录。在 POSTMAN 上测试相同的事务工作正常,但在我的 Xamarin Forms 移动应用程序中不起作用。 GetStringAsync 方法在 POSTMAN 和我的移动应用程序上都可以正常工作。我不知道为什么 PostAync 不起作用。请帮忙!
这是调用 PostAsync 的事件处理程序方法:
async void OnAdd(object sender, EventArgs e)
{
// This item is to be posted to the Azure database.
var tblmoney_item = new TblMoney
{
RecordDate = Convert.ToDateTime("7-26-2020"),
ItemDesc = "coffee",
AmountOut = 4500, // The currency unit is in KRW. (KRW 4,500 = US$4).
SpentTypeId = 3
};
// Serialize the item in JSON format.
var content = JsonConvert.SerializeObject(tblmoney_item);
// POST the item to the URL. Works fine on POSTMAN, but does NOT work on my mobile app.
await _client.PostAsync(Url, new StringContent(content));
// Refresh the list view.
_tblmoney_items.Insert(0, tblmoney_item);
}
这是上面变量(属性)的 MainPage 类中的声明:private const string Url = "https://testwebapi.azurewebsites.net/tblmoney";
private HttpClient _client = new HttpClient();
private ObservableCollection<TblMoney> _tblmoney_items;
该项目的类声明如下:public partial class TblMoney
{
public int Id { get; set; }
public DateTime? RecordDate { get; set; }
public string ItemDesc { get; set; }
public int? AmountOut { get; set; }
public int? SpentTypeId { get; set; }
public virtual TblSpentType SpentType { get; set; }
}
这是 REST Web API 项目中的 Controller Class,它是一个 ASP.Net Core Web Application 项目。[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class TblMoneyController : ControllerBase
{
private mynotedbContext _context = new mynotedbContext();
[HttpGet]
public IEnumerable<TblMoney> Get()
{
// get all tblMoney items.
return _context.TblMoney.ToList();
}
[HttpPost]
public IActionResult Post([FromBody]TblMoney tblmoney_item)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.TblMoney.Add(tblmoney_item);
_context.SaveChanges(true);
return StatusCode(StatusCodes.Status201Created);
}
}
数据库上下文如下所示:public partial class mynotedbContext : DbContext
{
public mynotedbContext()
{
}
public mynotedbContext(DbContextOptions<mynotedbContext> options)
: base(options)
{
}
public virtual DbSet<TblMoney> TblMoney { get; set; }
...
最佳答案
(来自评论)
我建议你设置 Content-Type
标题到 application/json
- 您可以通过在客户端上设置 header 或使用声明类型的 stringcontent 重载来执行此操作:例如new StringContent(content, Encoding.UTF8, "application/json"))
关于c# - HttpClient PostAsync() 不起作用而 POSTMAN 工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63096177/