在 blazor returns 中发布异常说明 "The JSON value could not be converted to System.Int32."

Posting in blazor returns exception stating that "The JSON value could not be converted to System.Int32."

我是 Blazor 的新手,在尝试 post 获取具有身份验证令牌的数据时遇到以下问题:在 API 调用时,解除了异常消息“JSON 值无法转换为 System.Int32。路径:$ | LineNumber:0 | BytePositionInLine:1.

这是我的 blazor 页面代码隐藏中的代码:

public partial class ContactCreate : AuthenticatedPageBase
{
    [Inject]
    public IContactDataService ContactDataService { get; set; }

    [Inject]
    public ICountryDataService CountryDataService { get; set; }

    public Contact.Post Model { get; set; } = new Contact.Post();

    protected string CountryIdString { get; set; } = string.Empty;

    protected string TokenString { get; set; } = string.Empty;

    public string ErrorMessage { get; set; } = string.Empty;

    protected List<Country.ListItem> Countries { get; set; } = new List<Country.ListItem>();

    protected async override Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        Countries = (await CountryDataService.GetCountryListAsync(Token.Token)).ToList();
        TokenString = Token.Token;
    }

    protected async Task HandleValidSubmit()
    {
        try
        {
            Model.CountryId = int.Parse(CountryIdString);
            var response = await ContactDataService.PostContactAsync(TokenString, Model);
            NavManager.NavigateTo("/contacts");
        }
        catch(Exception ex)
        {
            ErrorMessage = ex.Message;
        }
    }

    protected void HandleInvalidSubmit()
    {
        ErrorMessage = "Le formulaire n'est pas valide. Veuillez réessayer.";
    }
}

这里是数据服务中的相关代码:

public async Task<int> PostContactAsync(string token, Contact.Post model)
{
    var response = await PostAuthenticatedAsync<int>(token, Url, model);
    return response;
}

public async Task<T> PostAuthenticatedAsync<T>(string token, string url, object model)
{
    var jsonBody = model.ToJson();
    var request = new HttpRequestMessage()
    {
        RequestUri = new Uri(HttpClient.BaseAddress.ToString() + url),
        Method = HttpMethod.Post,
        Content = jsonBody
    };
    request.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
    var response = await HttpClient.SendAsync(request);
    return await response.FromJson<T>(Options);
}

...以及将对象序列化为 json 的扩展方法:

public static StringContent ToJson(this object o)
{
    return new StringContent(JsonSerializer.Serialize(o), Encoding.UTF8, "application/json");
}

这是我正在传递的对象模型:

public class Contact
{
    public class Post
    {
        [MaxLength(50)]
        public string FirstName { get; set; }
        [MaxLength(50)]
        public string LastName { get; set; }
        [MaxLength(50)]
        public string CompanyName { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        [MaxLength(20)]
        public string PostCode { get; set; }
        [MaxLength(60)]
        public string Locality { get; set; }
        public int CountryId { get; set; }
    }
}

最后,这是我试图达到的 API 方法:

[HttpPost]
public async Task<ActionResult> PostContact(Contact.Post model)
{
    try
    {
        var createdId = await _contactRepository.CreateAsync(model);
        return Ok(new { Id = createdId });
    }
    catch (Exception ex)
    {
        return BadRequest(new { ex.Message });
    }
}

知道发生了什么或者这个神秘的错误消息背后有什么实际异常吗?

P.S。 :我知道确切的异常消息存在问题,但它涉及 .NET Core,而我的目标是 .NET Standard 2.1。我读过它,但它显然不适用于这种情况。

您没有返回 int(Id)。您正在返回一个匿名对象,其中包含一个名为 Id 的 int 属性。 尝试

return Ok(createdId);