javascript - 从 typescript 将值作为空字符串传递给 WEb API

标签 javascript c# angular typescript asp.net-web-api

我想从 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/

相关文章:

angular - 模拟 http promise 服务时出现 `then is not a function` 错误

javascript - CSS "position:fixed": mobile zoom

c# - 我可以使用 MonoTouch 将旧的 C# 桌面应用程序移植到 iPad 上吗?

c# - 如何在给定 UTC 时间和日期的情况下创建 DateTime 对象?

angular - 模块导入的意外值 'undefined'

javascript - Angular2 Http 请求

javascript - 在javascript中,是否有内置的错误代码?是否可以捕获内部错误?可以继续吗?

javascript - 如何仅使用几个插件加载 XRegExp?

javascript - jquery - 最近似乎不起作用

c# - 在 "params"中包含另一个参数 (C#)