0

I try to create a form with Html.BeginForm() helper. But it throws exceptions:

XmlException: Root element is missing.
System.Xml.XmlTextReaderImpl.Throw(Exception e)

CryptographicException: An error occurred while trying to encrypt the provided data. Refer to the inner exception for more information.
Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Protect(byte[] plaintext)

This is standard ASP.Net MVC Application. I changed the controller code, add view-model and view classes. That's all.

Controller:

public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Login(UserVM userVM)
        {
            return Json(userVM);
        }
    }

ViewModel:

public class UserVM
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }


    }

View:

@using WebApplication1.ViewModels
@model UserVM

@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.TextBoxFor(m=>m.Email)
    @Html.PasswordFor(m=>m.Password)
}

This is what I get: Screenshot of exception page

What I am doing wrong?

Mykola Petiukh
  • 319
  • 1
  • 10
  • 1
    When and where do you get that exception? – SᴇM Apr 18 '19 at 12:37
  • @SᴇM when I try open page which should return this view. I record video for example https://youtu.be/yVmz1YwWoV8 – Mykola Petiukh Apr 18 '19 at 12:45
  • Is your config correct? No need of video, just exception message and when/where it occurs (video is some next level stuff). – SᴇM Apr 18 '19 at 12:47
  • @SᴇM what you mean? – Mykola Petiukh Apr 18 '19 at 12:49
  • Check [this post](https://stackoverflow.com/questions/3772486/how-to-fix-root-element-is-missing-when-doing-a-visual-studio-vs-build). – SᴇM Apr 18 '19 at 12:51
  • @SᴇM when i comment ```@using (Html.BeginForm("Login", "Home", FormMethod.Post))``` block it works fine – Mykola Petiukh Apr 18 '19 at 12:52
  • Well, you need also to remove `@` from the beginning of Html's inside `using` block. – SᴇM Apr 18 '19 at 12:53
  • @SᴇM no, it's the correct syntax – Mykola Petiukh Apr 18 '19 at 12:59
  • Given the issue is around key management not being able to read some XML file, I'm guessing this has something to do with `AntiForgeryToken`. Try commenting that out to test? – Cory Nelson Apr 18 '19 at 15:55
  • @CoryNelson same result – Mykola Petiukh Apr 18 '19 at 16:22
  • @mykmykpet , I test your code ,and it worked.Did you try to create a new simple project to test ? [Here](https://microsoftapc-my.sharepoint.com/:u:/g/personal/v-xuelc_microsoft_com/EawDazZbcV5MiVCTRJQC1kQBAEvc8A0DmrVoEq71oL6aHg?e=UNzjQg) is my demo , you could check the difference . If you still have the problem , could yo share the sample demo ? – Xueli Chen Apr 19 '19 at 10:37

0 Answers0