删除 HttpParams 中的空参数

Ana*_*and 8 query-string querystringparameter asp.net-core-webapi asp.net-core-2.0 angular

我有一个标准对象,它的某些属性可以为空,如果我不做任何事情,查询字符串包括那些&p=undefined不受欢迎的,因为在 WebApi 中,这些来自"null"而不是null 因此在 Angular 客户端中给出

      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);
Run Code Online (Sandbox Code Playgroud)

我可以得到查询字符串

http://localhost:63037/api/exposureRuns/data/?id=3&secsymb=undefined&fund=EL&esectype=SWAP_CDS
Run Code Online (Sandbox Code Playgroud)

有没有办法从查询字符串中排除未定义的参数?

小智 5

如果它们的值为(与根本不在对象中的键不同delete),您应该使用 JavaScript (MDN)关键字在客户端过滤它们undefined

if (queryObject.secsymb === undefined) {
  delete queryObject.secsymb;
}
Run Code Online (Sandbox Code Playgroud)

然后在控制器方法中使用默认方法参数:

GetExposureRunsData(int id, string fund, SecType sectype, string secsymb = null)
Run Code Online (Sandbox Code Playgroud)

如果您确保不包含查询字符串参数,那么您的参数将默认为 null