HttpClient的PostAsync()方法无法工作,而POSTMAN可以正常工作。

4
我正在尝试在我的Azure数据库帐户上发布一条项目。我编写并发布了一个ASP.Net Core Web应用程序到Azure帐户,该应用程序实现了Get、Post、Put和Delete等方法。在我的Xamarin Forms项目中,我试图调用HttpClient PostAsync方法来创建(post)一个记录到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应用程序项目。
[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);
    }
}

这个 DB 上下文看起来像这样:

public partial class mynotedbContext : DbContext
{
    public mynotedbContext()
    {
    }

    public mynotedbContext(DbContextOptions<mynotedbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<TblMoney> TblMoney { get; set; }
...

1
你遇到了什么异常? - devtoka
在哪个环节出现了问题?a.根本没有触发post方法?b.方法被触发,但在“ModelState.IsValid”处失败了?c.大约在“_context”附近出现了问题。 - devtoka
什么出了问题? - Vivek Nuna
1
我的第一个猜测是Content-Type头似乎没有设置为“application/json”...你可以在客户端上设置头,或者查看new StringContent(content, Encoding.UTF8, "application/json")) - Caius Jard
使用类似Wireshark或Fiddler的嗅探工具,将第一个请求与Postman和C#进行比较。让C#看起来像Postman一样。C#中的默认标头与Postman不同。 - jdweng
显示剩余4条评论
1个回答

4

建议您将Content-Type头设置为application/json - 您可以在客户端上设置标头,也可以使用声明类型的stringcontent的重载:例如new StringContent(content, Encoding.UTF8, "application/json"))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接