我想从 javascript 向 C# web api 传递一个空字符串。 但是当我从 typescript 传递空字符串时,我在 webapi 参数中得到 null 。 如何传递空字符串?
这是我的客户端 web api 调用:
public ChangePassword(username: string, oldPassword: string, newPassword: string) {
const oldPwd = (oldPassword === null || oldPassword === undefined) ? '' : oldPassword;
const newPwd = (newPassword === null || newPassword === undefined) ? '' : newPassword;
const endPointUrl: string = this.webApi.EndPoint + '/Authentication/ChangePassword';
const parameters = new HttpParams()
.set('username', username)
.set('oldPassword', oldPwd)
.set('newPassword', newPwd);
return this.httpClient.post(endPointUrl, '', { params: parameters });
}
我的 web api 是
[HttpPost]
public void ChangePassword(string userName, string oldPassword, string newPassword)
{
WebServiceFault fault = _securityManager.ChangePassword(userName, oldPassword, newPassword);
if (fault == null)
{
return;
}
throw WebApiServiceFaultHelper.CreateFaultException(fault);
}
当我将 null 作为旧密码和新密码的参数传递给 ChangePassword()
方法时,我在 web api 方法中将字符串作为 null 而不是获取空字符串。
最佳答案
您正在执行一个post 请求,因此请考虑通过body 将数据作为第二个参数而不是查询参数传递。
public ChangePassword(username: string, oldPassword: string, newPassword: string) {
const oldPwd = (oldPassword === null || oldPassword === undefined) ? '' : oldPassword;
const newPwd = (newPassword === null || newPassword === undefined) ? '' : newPassword;
const endPointUrl: string = this.webApi.EndPoint + '/Authentication/ChangePassword';
return this.httpClient.post(endPointUrl, { username, oldPwd, newPwd });
}
并使用 [FromBody]
属性进入 API。
[HttpPost]
public void ChangePassword([FromBody]string userName, [FromBody]string oldPassword, [FromBody]string newPassword)
{
WebServiceFault fault = _securityManager.ChangePassword(userName, oldPassword, newPassword);
if (fault == null)
{
return;
}
throw WebApiServiceFaultHelper.CreateFaultException(fault);
}
此外,最好有一个描述更改密码模型的模型,并将数据作为模型获取,而不是作为单独的参数。有点像
[HttpPost]
public void ChangePassword([FromBody]ChangePasswordModel model)
关于javascript - 从 typescript 将值作为空字符串传递给 WEb API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726478/