Error encountered when AJAX/ASP.NET Core MVC/DevExtreme POST back results in a faulty URL (Error/Error?code=22)

Incorporating Ajax into my MVC application allows me to initiate a POST request when the user clicks on the logout button. The goal is to redirect the user back to the Login page and route them to the HttpPost method in the controller. However, I encounter an error when attempting to log out using Ajax:

This localhost page can’t be found No webpage was found for the web address: http://localhost/myApp/Error/Error?code=22

PageHeader.cshtml

...
 items.Add()
        .Widget(w => w
        .Button()
        .Type(ButtonType.Normal)
        .StylingMode(ButtonStylingMode.Text)
        .Text("Logout")
        .ID("logoutbutton")
        .OnClick("logoutOnClick")
            )
            .CssClass("toolbar-button")
            .LocateInMenu(ToolbarItemLocateInMenuMode.Auto)
            .Location(ToolbarItemLocation.After);
    })
    )
...
<script type="text/javascript">
        function logoutOnClick () {
            if (confirm('Are you sure you want to logout?')) {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("Login", "Account")'
                    
                });
            }
        }
</script>

AccountController.cs

...
        [HttpGet]
        public IActionResult Login() { return View(new LoginModel()); }

     
        [HttpPost, ValidateAntiForgeryToken]
        public IActionResult Login(LoginModel userModel)
        {
            bool? isAuthenticated = false;

           ...

Answer №1

    [HttpPost, ValidateAntiForgeryToken]
    public IActionResult Login(LoginModel userModel)

Your code includes the use of the ValidateAntiForgeryToken attribute to prevent forgery of a request. If you are making JQuery Ajax calls to the method above, make sure to include the RequestVerificationToken in the request header.

To configure the antiforgery service in the Startup.ConfigureServices method:

        //configure the antiforgery service to look for the X-CSRF-TOKEN header. To prevent cross-site request forgery.
        services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");  

In the Login.cshtml page, within the Ajax beforeSend function, set the RequestVerificationToken:

@model WebApplication6.Models.LoginModel
 
<div class="row">
    <div class="col-md-4">
        <form asp-action="Login">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            ...
            <div class="form-group">
                <input type="button" value="Create" id="btnCreate" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

    <script>
        $(function () {
            $("#btnCreate").click(function () { 
                $.ajax({
                    url: '/Account/Login',
                    type: 'Post',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    data: { "UserName": "AA", "Password": "pass" },
                    success: function (result) {
                        alert("sucess");
                    },
                    error: function (xhr, status) {
                        alert(status);
                    }
                });
            });
        })
    </script>
}

You can now access the action method via Ajax as shown in this screenshot:

https://i.sstatic.net/E5QLf.gif

If you remove the ValidateAntiForgeryToken attribute in the controller, you won't need to set the RequestVerificationToken in the request header anymore.

Modified code without ValidateAntiForgeryToken attribute:

    [HttpPost]
    public IActionResult Login(LoginModel userModel)
    {
        bool? isAuthenticated = false;
        return View();
    }

JQuery script for the updated code:

        $.ajax({
                url: '/Account/Login',
                type: 'Post', 
                data: { "UserName": "AA", "Password": "pass" },
                success: function (result) {
                    alert("sucess");
                },
                error: function (xhr, status) {
                    alert(status);
                }
            });

For more information on preventing Cross-Site Request Forgery attacks in ASP.NET Core, refer to this resource: Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core

Answer №2

Please ensure that your ajax URL is correctly configured:

  url:  "/MyApp/Account/Login",

I am not able to retrieve any data from your ajax request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building a JavaScript application with Node.js and MySQL to seamlessly interact with both offline and online databases

As I develop a JavaScript web-app, my plan is to utilize Node.js for connecting the app with an existing MySQL database. My initial question pertains to the structure of the Node code: should it be written in the same .js file as my application or kept se ...

Popup notification system using AJAX and jQuery for Facebook likes

What is the most efficient way to display a popup message box (similar to Facebook) using Ajax? I have my message form and processing code in separate files as I prefer not to clutter every page with inline code. I have experimented with different option ...

Use error list substitution as opposed to adding Json

Hi there! I have the JSON code below that is used to validate a form. If incorrect data is entered more than once when the create button is clicked, it appends all the data again and still displays the original errors. Is there a way to remove the curren ...

Issues with React Material UI Dialog Displaying Incorrect Information

As I experiment with React Material UI dialog boxes, I've encountered an issue that has me puzzled. I have an object 'a', and when I click on a button in a list, it should display the respective ID number. However, instead of showing the cor ...

Utilize JavaScript API for generating and retrieving XSD schema and XML documents

Are there any stable JavaScript APIs that can be used to generate and read XSD schemas and XML documents? My specific requirement is: Allow one user to define/generate an XSD schema through a UI. Later, allow another user to provide appropriate data ...

Working with multi-line HTML content within Javascript

I am currently using JavaScript to define the behavior of a button on a website. I want the button to add new HTML content to a specific part of the page, and I would like to use the MVC extension method Html.EditorFor to create this new HTML. Here is wha ...

Navigating the realm of JavaScript and managing the uncertainties of floating point precision

I am exploring the development of a browser multiplayer game utilizing rollback netcode that operates a deterministic simulation on the clients. I successfully prototyped the netcode in Flash, but encountered a floating point roadblock along the way. As f ...

I seem to be experiencing some confusion with labeling in my pie chart and doughnut chart using Chart.js. Additionally, I am unable to properly display the charts themselves

Struggling to generate charts using vue js. The chart is displaying with crossed labels instead of the actual chart. I'm puzzled about what could be causing this issue. https://i.sstatic.net/5hZXR.png Supposedly, this should be a pie chart. However, ...

Leveraging Ninject for MongoDB: Efficient Dependency Resolution for Repository

It seems like I have hit a roadblock in understanding how Ninject operates across different assemblies. I have an asp.net mvc website that is referencing a Core.dll which houses my domain objects, repository, and some services. One of my domain objects has ...

Utilizing Inquiries within Arrays

I've been working on a quiz application and I have successfully built the array with questions and answers. However, I'm facing some challenges in getting the next question to display after clicking the submit button. Here is a snippet of the cod ...

A guide on retrieving query string parameters from a URL

Ways to retrieve query string parameters from a URL Example Input - www.digital.com/?element=fire&solution=water Example Output - element = fire solution = water ...

If the variable is not defined, then utilize a different one

There are two scopes: $scope.job and $scope.jobs. I also have a variable called job; If $scope.job is undefined, I want $scope.jobs to be assigned to the job variable using the following code: var job = $scope.jobs. However, if $scope.job is defined, the ...

Using jQuery's .text() function transforms my h1 element into regular text once a number is inputted

I am facing an issue with the following code snippet: <li id="machine" ><h1>Machine</h1></li> <li id="player"><h1>Player</h1></li> It displays as shown in the image below: https://i.sstatic.net/CR3Ut.png ...

Revamp a dynamically generated class using ajax

I am currently developing an email-based application using PHP and the CodeIgniter framework. My goal is to change the status of unread messages to read when they are clicked on, utilizing two different classes: read0 and read1. While I can view the messag ...

Sending a result back to a Silverlight user control from a slightly intricate JavaScript function

I am working on a Silverlight user control that contains a textbox and a button. Within this Silverlight page, there can be multiple instances of these user controls. My goal is to have a JavaScript function trigger when the button is clicked. This functi ...

Is there a simple method to extract all components from an SVG document and insert them into an HTML text box?

Looking to provide users with the option to manually edit an SVG document. Is there a direct way to utilize DOM to extract all elements from an SVG document and place them in a text box? Attempted using innerHTML, but it doesn't work for SVG. Is the ...

Creating an accordion using an array in JavaScript: A step-by-step guide

I'm experimenting with creating an accordion using HTML, CSS, and JavaScript. I've managed to set it up, however, the array text is only displaying in one accordion item and the buttons are not functioning for each individual accordion. Is there ...

Is it possible to use Ajax to upload images on a website?

I am encountering an issue with uploading images using $.ajax in PHP. The error message I'm getting is: undefined index:files Below are the details of my HTML and JS code: <form id="image_form" enctype="multipart/form-data"> <input t ...

Pass the most recent properties to the mousemove event handler

I am currently developing a click-and-drag feature, which involves: setting up a moveListener on the onMouseDown event having the moveListener trigger an action that updates certain props of the component (props.whichChange) cleaning up the mouseUp event ...

How can I improve the efficiency of my ajax requests in jQuery using PHP and

I currently have a button that, when clicked, will send a $.post() request to add an item to the basket. I would like for it to only send one request if the user clicks the button quickly ten times in a row, with the count being updated appropriately. The ...