angularquery-stringasp.net-core-2.0asp.net-core-webapiquerystringparameter

Remove null params in HttpParams


I have a criteria object for which some attributes can be null, if I don't do anything the query string include those like &p=undefined which is not desirable since at the WebApi these come as"null" instead of null So given this in the Angular client

      return this._http
          .get<ExposureDifference[]>(AppSettings.ExposureRunDataQueryString, {params : <any>criteria, withCredentials: true}) 
          .catch<any, ExposureDifference[]>(this._trace.handleError("GET " + AppSettings.ExposureRunDataQueryString + criteria, []))
          .finally(() => this.isLoading = false);

I could get the query string as

http://localhost:63037/api/exposureRuns/data/?id=3&secsymb=undefined&fund=EL&esectype=SWAP_CDS

Is there a way to exclude the undefined parameters from the query string?


Solution

  • You should filter them client side using JavaScript's delete (MDN) keyword if they have a value of undefined (which is different than the key not being in the object at all):

    if (queryObject.secsymb === undefined) {
      delete queryObject.secsymb;
    }
    

    and then use a default method parameter in your controller method:

    GetExposureRunsData(int id, string fund, SecType sectype, string secsymb = null)
    

    If you ensure that the query string parameter is not included then your parameter will default to null