Web API complex parameter properties are all null

前端 未结 18 1499
长情又很酷
长情又很酷 2020-11-30 04:18

I have a Web API service call that updates a user\'s preferences. Unfortunately when I call this POST method from a jQuery ajax call, the request parameter object\'s proper

相关标签:
18条回答
  • 2020-11-30 05:15

    I face this problem this fix it to me

    1. use attribute [JsonProperty("property name as in json request")] in your model by nuget package newton
    2. if you serializeobject call PostAsync only

    like that

    var json = JsonConvert.SerializeObject(yourobject);
    var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
    var response = await client.PostAsync ("apiURL", stringContent);
    
    1. if not work remove [from body] from your api
    0 讨论(0)
  • 2020-11-30 05:20
      public class CompanyRequestFilterData
        {
                 public string companyName { get; set; }
                 public string addressPostTown { get; set; }
                 public string businessType { get; set; }
                 public string addressPostCode{ get; set; }
                 public bool companyNameEndWith{ get; set; }
                 public bool companyNameStartWith{ get; set; }
                 public string companyNumber{ get; set; }
                 public string companyStatus{ get; set; }
                 public string companyType{ get; set; }
                 public string countryOfOrigin{ get; set; }
                 public DateTime? endDate{ get; set; }
                 public DateTime? startDate { get; set; }
    }
    

    webapi controller

        [HttpGet("[action]"),HttpPost("[action]")]
        public async Task<IEnumerable<CompanyStatusVm>> GetCompanyRequestedData(CompanyRequestFilterData filter)
        {}
    

    jsvascript/typescript

    export async function GetCompanyRequesteddata(config, payload, callback, errorcallback) {
    await axios({
        method: 'post',
        url: hostV1 + 'companydata/GetCompanyRequestedData',
        data: JSON.stringify(payload),
        headers: {
            'secret-key': 'mysecretkey',
            'Content-Type': 'application/json'
        }
    })
        .then(res => {
            if (callback !== null) {
                callback(res)
            }
        }).catch(err => {
            if (errorcallback !== null) {
                errorcallback(err);
            }
        })
    

    }

    this is the working one c# core 3.1

    my case it was bool datatype while i have changed string to bool [companyNameEndWith] and [companyNameStartWith] it did work. so please check the datatypes.

    0 讨论(0)
  • 2020-11-30 05:21

    As this issue was troubling me for almost an entire working day yesterday, I want to add something that might assist others in the same situation.

    I used Xamarin Studio to create my angular and web api project. During debugging the object would come through null sometimes and as a populated object other times. It is only when I started to debug my project in Visual Studio where my object was populated on every post request. This seem to be a problem when debugging in Xamarin Studio.

    Please do try debugging in Visual Studio if you are running into this null parameter problem with another IDE.

    0 讨论(0)
  • 2020-11-30 05:22

    I have also facing this issue and after many hours from debbug and research can notice the issue was not caused by Content-Type or Type $Ajax attributes, the issue was caused by NULL values on my JSON object, is a very rude issue since the POST neither makes but once fix the NULL values the POST was fine and natively cast to my respuestaComparacion class here the code:

    JSON

     respuestaComparacion: {
                                anioRegistro: NULL, --> cannot cast to BOOL
                                claveElector: NULL, --> cannot cast to BOOL
                                apellidoPaterno: true,
                                numeroEmisionCredencial: false,
                                nombre: true,
                                curp: NULL, --> cannot cast to BOOL
                                apellidoMaterno: true,
                                ocr: true
                            }
    

    Controller

    [Route("Similitud")]
    [HttpPost]
    [AllowAnonymous]
    
    public IHttpActionResult SimilitudResult([FromBody] RespuestaComparacion req)
    {
       var nombre = req.nombre;
    }
    

    Class

    public class RespuestaComparacion
        {
            public bool anioRegistro { get; set; }
            public bool claveElector { get; set; }
            public bool apellidoPaterno { get; set; }
            public bool numeroEmisionCredencial { get; set; }
            public bool nombre { get; set; }
            public bool curp { get; set; }
            public bool apellidoMaterno { get; set; }
            public bool ocr { get; set; }
        }
    

    Hope this help.

    0 讨论(0)
  • 2020-11-30 05:25

    This seems to be a common issue in regards to Asp.Net WebAPI.
    Generally the cause of null objects is the deserialization of the json object into the C# object. Unfortunately, it is very difficult to debug - and hence find where your issue is.
    I prefer just to send the full json as an object, and then deserialize manually. At least this way you get real errors instead of nulls.
    If you change your method signature to accept an object, then use JsonConvert:

    public HttpResponseMessage Post(Object model)
            {
                var jsonString = model.ToString();
                PreferenceRequest result = JsonConvert.DeserializeObject<PreferenceRequest>(jsonString);
            }
    
    0 讨论(0)
  • 2020-11-30 05:25

    My issue was not solved by any of the other answers, so this solution is worth consideration:

    I had the following DTO and controller method:

    public class ProjectDetailedOverviewDto
    {
        public int PropertyPlanId { get; set; }
    
        public int ProjectId { get; set; }
    
        public string DetailedOverview { get; set; }
    }
    
    public JsonNetResult SaveDetailedOverview(ProjectDetailedOverviewDto detailedOverview) { ... }
    

    Because my DTO had a property with the same name as the parameter (detailedOverview), the deserialiser got confused and was trying to populate the parameter with the string rather than the entire complex object. The solution was to change the name of the controller method parameter to 'overview' so that the deserialiser knew I wasn't trying to access the property.

    0 讨论(0)
提交回复
热议问题