我想从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。
发布于 2018-04-09 14:08:00
您正在执行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]属性获取应用程序接口。
[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)发布于 2018-08-03 20:19:21
不是作为单独的参数传递,而是使用如下模型,
public class ChangePasswordModel
{
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string userName { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string oldPassword { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string newPassword { get; set; }
}使用它作为,
[HttpPost]
public void ChangePassword([FromBody]ChangePasswordModel model)您的模型类的属性上的DisplayFormat属性将执行您想要的操作。
https://stackoverflow.com/questions/49726478
复制相似问题