在 Angular 服务中,我使用 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 核心项目。 Controller 中调用的代码:
[HttpGet("[action]")]
public async Task<JsonResult> Get(string phone) // receiving " 123456"
{
return Json(await PhoneSearchLogic.GetAsync(phone));
}
[更新] Noémi Salaun 的解释非常好 - 但我想知道更改参数是否是“设计”的预期行为?或者是 ASP.NET Core Controller 的问题,它不应该对 + 号(和其他符号)进行转义?
最佳答案
源码中可以看到common/http/src/params.ts , HttpParams
使用默认编码器 HttpUrlEncodingCodec
。
HttpUrlEncodingCodec
使用 native encodeURIComponent
函数,但随后取消编码一些符号以满足 RFC 规范( native JS 实现不遵循)。
所以如果你想保持你的 +
符号编码,你可以在使用 HttpParams
之前手动编码它,或者你可以覆盖 HttpParameterCodec
您自己的实现并通过 HttpParamOptions.encoder
属性传递它。
所有这些在现已弃用的 Http
服务中得到了更好的解释。使用它的 UrlSearchParams
和 QueryEncoder
。
源码中可以看到http/src/url_search_params.ts
By default,
QueryEncoder
encodes keys and values of parameters usingencodeURIComponent
, and then un-encodes certain characters that are allowed to be part of the query according to IETF RFC 3986: https://www.rfc-editor.org/rfc/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.
关于angular - 如何逃避 Angular HttpParams?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49438737/