Issue
In an Angular Service I'm using HttpParams to send a string to the service:
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 });
}
When calling get() with +123456
as parameter I'll get 123456
in the receiving service. So somewhere on the way the +
gets converted to a space.
Do I need to escape HttpParams to get them unchanged to the service?
If it matters, the backend is an asp.net core project. The called code in the controller:
[HttpGet("[action]")]
public async Task<JsonResult> Get(string phone) // receiving " 123456"
{
return Json(await PhoneSearchLogic.GetAsync(phone));
}
[Update] Very good explanation by Noémi Salaün - but I wonder if changing the parameters is expecteded behaviour "by design"? Or is the problem the ASP.NET Core controller, which should not unescape the + sign (and others)?
Solution
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 through 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 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.
Answered By - Noémi Salaün
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.