javascript - ASP.NET Core 获取 POST FormData() application/x-www-form-urlencoded

标签 javascript c# asp.net-core fetch

我要验证。 Controller 不想接收数据。 Eat 删除 ValidateAntiForgeryToken,然后接受 null。

在 Html.AntiForgeryToken() View 中。

enter image description here

这是我的代码:

getDataTable = async (e) => {
    try {
        const { Login, Password } = this.state;
        var data = new FormData();
        data.append("Login", Login);
        data.append("Password", Password);
        data.append("__RequestVerificationToken", this.props.__RequestVerificationToken);
        const response = await fetch(urlControlActionAccountLogin, {
            method: "POST", // *GET, POST, PUT, DELETE, etc.
            mode: "cors", // no-cors, cors, *same-origin
            cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
            credentials: "same-origin", // include, *same-origin, omit
            headers: {
                "Accept": "application/json, application/xml, text/plain, text/html, *.*",
                //"Content-Type": "application/json",
                "Content-Type": "application/x-www-form-urlencoded",
            },
            redirect: "follow", // manual, *follow, error
            referrer: "no-referrer", // no-referrer, *client
            body: data, // body data type must match "Content-Type" header
        });
        const json = await response.json();
        //this.setState({ textarea: json.description });
        this.setState({
            isLoaded: true,
        });
        console.log(json);
    } catch (error) {
        this.setState({
            isLoaded: true,
            error
        });
        console.error(error);
    }
};

C# Controller ASP.net 核心 2.2 JS应该发送登录密码数据,controller会接受

[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
[AllowAnonymous]
[ValidateAntiForgeryToken] 
public async Task<IActionResult> Login([FromForm]string _model) //[FromBody]LoginModel model
{
    var model = JsonConvert.DeserializeObject<LoginModel>(_model); //[FromForm]string _model
    //var model = _model.ToObject<LoginModel>(); //[FromForm]JObject _model
    var a = db.GetUserContext();

    if (ModelState.IsValid)
    {
        User user = await db.Users.FirstOrDefaultAsync(u => u.Login == model.Login && u.Password == model.Password);
        if (user != null)
        {
            await Authenticate(model.Login); // аутентификация

            return Json(new
            {
                user
            });
        }
        ModelState.AddModelError("", "Некорректные логин и(или) пароль");
    }
    return View(model);
}

最佳答案

由于您使用 FormData 发送数据,因此您请求的 Content-Type 应该是 application/form-data。但是正如您在浏览器网络选项卡中看到的那样,实际数据值之间存在一些奇怪的值

-----WebKitFormBoundarySomeValue

这是一个分隔数据条目的边界Content-Type header 的实际值应该是application/form-data; boundary=-----WebKitFormBoundarySomeValue。由于这个值是由浏览器随机生成的,你不能手动设置它,你应该省略 Content-Type header ,浏览器会为你设置它。

headers: {
    "Accept": "application/json, application/xml, text/plain, text/html, *.*"
    //no content-type
}

在您的 Controller 代码中使用[FromForm] 属性将请求数据读取为表单数据。在这种情况下,您应该放弃使用 Consumes 属性,因为您无法指定正确的 Content-Type 值,因为它因请求而异。

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken] 
public async Task<IActionResult> Login([FromForm]LoginModel model)

关于javascript - ASP.NET Core 获取 POST FormData() application/x-www-form-urlencoded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146601/

相关文章:

JavaScript setInterval 循环不保存变量

c# - WPF 在列表框中拖放,带有拖放位置的预览阴影

c# - 获取之前在应用程序 c# 中抛出的异常?

c# - 我可以在非 ASP.NET Core 的 .NET.core 应用程序中使用 HttpClientFactory 吗?

c# - 文件未找到异常 : Could not load

javascript - 是否可以在 JavaScript 中创建 "weak reference"?

javascript - 使用 Spring Security 保护 Web 应用程序免受 CSRF 攻击

javascript - 无法读取 undefined object

c# - 将程序集作为模块/插件加载,同时避免重复和脆弱性

c# - OpenRasta 是否支持 HEAD HTTP 方法?