[英]HttpClient PostAsync() doesn't work while POSTMAN works fine
我正在尝试在我的 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 class 中的声明:
private const string Url = "https://testwebapi.azurewebsites.net/tblmoney";
private HttpClient _client = new HttpClient();
private ObservableCollection<TblMoney> _tblmoney_items;
该项目的 Class 声明如下:
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; }
}
Here's the Controller Class in the REST Web API project, which is an ASP.Net Core Web Application project.
[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
header 设置为application/json
- 您可以通过在客户端上设置 header 或使用声明类型的 stringcontent 重载来执行此操作:例如new StringContent(content, Encoding.UTF8, "application/json"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.