1

I want to validate. The controller does not want to receive data. Eat remove ValidateAntiForgeryToken, then accepts null.

In view Html.AntiForgeryToken().

enter image description here

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

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

1 Answer 1

3

Since you are sending data using FormData the Content-Type of your request should be 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. And the actual value of Content-Type header should be 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.

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. And you should abandon using Consumes attribute in this case since you cannot specify correct Content-Type value because it varies between requests.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken] 
public async Task<IActionResult> Login([FromForm]LoginModel model)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.