如何逃避角度HttpParams?

时间:2018-03-22 21:25:28

标签: angular http

在Angular Service中我使用HttpParams向服务发送字符串:

get(phone: string): Observable<PhoneSearchResponse> {
    let params = new HttpParams();
    params = params.append("phone", phone); // sending "+123456"
    return this._http.get<PhoneSearchResponse>(`${this._apiurl}/Get`, { params: params });
}

当使用+123456作为参数调用get()时,我将在接收服务中获得123456。所以在+被转换为空间的路上。

我是否需要逃避HttpParams才能使它们保持不变?

如果重要,后端是一个asp.net核心项目。控制器中的被调用代码:

[HttpGet("[action]")]
public async Task<JsonResult> Get(string phone) // receiving " 123456"
{
  return Json(await PhoneSearchLogic.GetAsync(phone));
}

[更新]NoémiSalaün非常好的解释 - 但我想知道改变参数是否是“设计”的预期行为?或者问题是ASP.NET核心控制器,它不应该忽略+符号(和其他人)?

3 个答案:

答案 0 :(得分:5)

As you can see in the source code common/http/src/params.ts, HttpParams uses a default encoder HttpUrlEncodingCodec.

HttpUrlEncodingCodec uses the native encodeURIComponent function but then un-encodes some symbole to meet the RFC specification (not followed by the native JS implementation).

So if you want to keep your + symbol encoded you can encode it manually before using HttpParams, or you can override the HttpParameterCodec with your own implementation and pass it threw the HttpParamOptions.encoder attribute.

All this was better explained in the now deprecated Http service. With its UrlSearchParams and the QueryEncoder.

As you can see in the source code http/src/url_search_params.ts

By default, QueryEncoder encodes keys and values of parameters using encodeURIComponent, and then un-encodes certain characters that are allowed to be part of the query according to IETF RFC 3986: https://tools.ietf.org/html/rfc3986.

These are the characters that are not encoded: ! $ \' ( ) * + , ; A 9 - . _ ~ ? /

If the set of allowed query characters is not acceptable for a particular backend, QueryEncoder can be subclassed and provided as the 2nd argument to URLSearchParams.

答案 1 :(得分:0)

而是一个纯Javascript解决方案,

const string = 'text+that+has+plus+signs';

为了安全地进行编码,(请注意encodeURIComponent很重要,因为btoa可以返回+

const enc = encodeURIComponent(btoa(string));
console.log(enc); //dGV4dCt0aGF0K2hhcytwbHVzK3NpZ25z

要解码并取回纯文本,

const dec = atob(decodeURIComponent(enc));    
console.log(dec); //text+that+has+plus+signs

我不是真的喜欢覆盖HttpUrlEncodingCodec只是为了逃避post参数中的+标志。

我希望这会对某人有所帮助。干杯:)

答案 2 :(得分:-2)

前段时间我遇到了这个问题,最后决定使用FormData代替HttpParams ...几乎在所有地方。我曾经依赖于FormData,尤其是在将文件发送到服务时,直到我使用HttpParams发送了一个带有+符号的字符串,并且+从未到达后端为止。它被一个空格代替。

所以只需替换

let params = new HttpParams();
params = params.append("phone", phone); // sending "+123456"

let params = new FormData();
params.append("phone", phone);