简体   繁体   English

ASP.NET Core提取POST FormData()应用程序/ x-www-form-urlencoded

[英]ASP.NET Core Fetch POST FormData() application/x-www-form-urlencoded

I want to validate. 我要验证。 The controller does not want to receive data. 控制器不想接收数据。 Eat remove ValidateAntiForgeryToken, then accepts null. 吃掉删除ValidateAntiForgeryToken,然后接受null。

In view Html.AntiForgeryToken(). 在视图中Html.AntiForgeryToken()。

在此处输入图片说明

Here is my code: 这是我的代码:

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 core 2.2 JS should send the login password data, and the controller will accept C#Controller ASP.net core 2.2 JS应该发送登录密码数据,并且控制器将接受

[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);
}

Since you are sending data using FormData the Content-Type of your request should be application/form-data . 由于您使用FormData发送数据,因此请求的Content-Type应该是application/form-data But as you can see in browser network tab there is some strange values between the actual data values 但是,正如您在浏览器的“网络”标签中看到的那样,实际数据值之间有些奇怪的值

-----WebKitFormBoundarySomeValue

This is a boundary separating your data entries. 这是分隔数据条目的boundary And the actual value of Content-Type header should be application/form-data; boundary=-----WebKitFormBoundarySomeValue Content-Type标头的实际值应为application/form-data; boundary=-----WebKitFormBoundarySomeValue application/form-data; boundary=-----WebKitFormBoundarySomeValue . application/form-data; boundary=-----WebKitFormBoundarySomeValue Since this value is generated randomly by a browser you cannot set it manually and you should just omit Content-Type header, browser will set it for you. 由于此值是由浏览器随机生成的,因此您无法手动设置它,而应该省略Content-Type标头,浏览器会为您设置它。

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

In your controller code use [FromForm] attribute to read request data as form data. 在您的控制器代码中,使用[FromForm]属性读取请求数据作为表单数据。 And you should abandon using Consumes attribute in this case since you cannot specify correct Content-Type value because it varies between requests. 并且在这种情况下,您应该放弃使用Consumes属性,因为您不能指定正确的Content-Type值,因为它在请求之间会有所不同。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 新的 FormData() “application/x-www-form-urlencoded” - new FormData() "application/x-www-form-urlencoded" 如何使用应用程序 / x-www-form-urlencoded 发送 axios 帖子? - How to send axios post with application / x-www-form-urlencoded? 使用 x-www-form-urlencoded content-type 将嵌套的 object 作为 formdata 发布 - post nested object as formdata using x-www-form-urlencoded content-type fetch()标头显示为application / x-www-form-urlencoded而不是application / json - fetch() header shows as application/x-www-form-urlencoded instead of application/json 如何使用 Fetch 发布 x-www-form-urlencoded 请求? - How do I POST a x-www-form-urlencoded request using Fetch? 如何使用 Fetch 发布 x-www-form-urlencoded 请求并使用答案? - How do I POST a x-www-form-urlencoded request using Fetch AND work with the answer? 使用application / x-www-form-urlencoded使用node.js在发布请求中发送数组 - Send Array in post request using node.js using application/x-www-form-urlencoded 使用Iron-ajax发布json对象作为application / x-www-form-urlencoded - Post json object with iron-ajax as application/x-www-form-urlencoded 如何在+呼叫后内容类型中转义+作为application / x-www-form-urlencoded - How to escape + in post call content type as application/x-www-form-urlencoded 在JS中,如何在给定URL和application / x-www-form-urlencoded字符串的情况下进行POST? - In JS, how to make a POST given a URL and a application/x-www-form-urlencoded string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM