【发布时间】:2018-04-09 06:04:16
【问题描述】:
我想将一个空字符串从 javascript 传递给 C# web api。 但是当我从打字稿传递空字符串时,我在 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。
【问题讨论】:
-
Suren 在下面指出了一些我会同意的细节。我将成为房间里的大象并问:您将空字符串传递给控制器的用例究竟是什么?做
string.IsNullOrEmpty检查还不够吗?还是您需要在代码中同时使用null和""案例? -
null 和 " " 有不同的含义。 null 表示用户没有正确调用 api," " 表示用户要设置空密码。
-
对它们有不同的用例是很合理的。我无法确定的是,您允许用户设置空密码..?如果你问我,那只是糟糕的设计。是否有任何理由为什么您需要让您的用户设置空密码?
-
无论哪种方式,在反序列化您的值时区分
string.Empty和null,this answer 会有帮助吗?
标签: javascript c# angular typescript asp.net-web-api