The controller function is not triggered if the user does not have administrator privileges

I have a code snippet in which my controller function is not being triggered for users who do not have the role of "Admin". Can someone help me identify where I went wrong? Just to clarify, the controller function works fine for users with the role of "Admin", but it does not get called for any other roles.

VIEW:

function acceptTerms() {        
    var userName = '@Html.ValueFor(m => m.UserName)';

    $.ajax({
        type: "POST",
        url: '@Url.Action("UpdateUserConnects", "User")',
        data: JSON.stringify({ userName: userName }),            
        contentType: "application/json; charset=utf-8",
        success: function (data) {               
            if (data == "Failed") {
                alert("failed");
            }
            else {
                var wnd = $("#wndTerms").data("kendoWindow");
                wnd.close();
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("AcceptTerms", "Account")',
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        window.location.href = data
                    }
               });
            }
        }
    });

}

CONTROLLER:

 [AcceptVerbs(HttpVerbs.Post)]
    public String UpdateUserConnects(string userName)
    {
        try
        {
            UsersService usersService = new UsersService();
            Users user = usersService.GetUserByUsername(userName);
            if (user != null) {
                user.previouslyConnected = true;
                usersService.UpdateUser(user);
            }               
        }
        catch (Exception e) {  
            return "Failed";
        }
        return "Success";
    }

Answer №1

If you come across this message at a later time:

MANAGER:

[Authorize]
public class UserController : BaseController {

    [AcceptVerbs(HttpVerbs.Post)]
    [AllowAnonymous]
    public String UpdateUserConnects(string userName)
    {
       try
       {
           UsersService usersService = new UsersService();
           Users user = usersService.GetUserByUsername(userName);
           if (user != null) {
               user.previouslyConnected = true;
               usersService.UpdateUser(user);
           }               
       }
       catch (Exception e) {  
           return "Failed";
    }
    return "Success";
}

The problem was that [Authorize] placed at the beginning of the page only permits individuals with an "Admin" role to access the functions within the controller by default.

To allow all users for a specific function, utilize [AllowAnonymous] as an attribute solely for that function.

To permit other role names, employ [Authorize(Roles = "OtherRole")

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

The use of Next.js v12 middleware is incompatible with both node-fetch and axios

I am facing an issue while developing a middleware that fetches user data from an external endpoint using Axios. Surprisingly, Axios is not functioning properly within the middleware. Below is the error message I encountered when using node-fetch: Module b ...

What is the reason for Bower consistently choosing to download the Angular version 1.5.9-build.5086+sha...?

Struggling to manage my front end dependencies using bower.json. No matter how I specify the version of Angular in bower, a different version is downloaded every time. The issue is that many functionalities in my code rely on previous versions of Angular, ...

The camera steadily advances in WebVR Cardboard using three.js technology, never stopping its forward movement

I've been experimenting with trying to create a smooth, continuous forward movement for the camera in a three.js/WebVR project, specifically with only a cardboard viewer needed. After much trial and error, I've discovered that the usual camera m ...

Vuejs Countdown Timer Powered by Moment.js

Currently, I am working on a vuejs page and I am looking to incorporate a countdown timer that counts down from 5 minutes (e.g. 5:00, 4:59, and so on). Although I have never used momentjs before, I have gone through the moment docs but I am finding it ch ...

How to delete an element from an array with UnderscoreJS

Here's a scenario: var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]; I'm looking to delete the element with id value of 3 from this array. Is there a method to achieve this without using splice? Perhap ...

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

An issue with JSPDF arises when used on mobile devices

Currently, I am working on a project to create a responsive web application, which involves utilizing JSPDF for generating PDF reports directly from HTML. For a demonstration of the functionality, you can check out this Demo. Unfortunately, when trying t ...

Tips for removing a specific object element in a nested array within mongoDB with expressjs

When I attempt to delete comments using the code below, the issue I am encountering is that all comments are being deleted instead of just the one I clicked on. Why is this happening? Here is the route code for deleting the comment: router.route("/delete ...

Issue encountered when attempting to batch delete documents within a subcollection: Error message displays "TypeError: n.indexOf is not a

When attempting to batch delete a document within a subcollection, I encounter some issues. There are scenarios where I may need to remove the same product document ID along with various history document IDs, or multiple product document IDs with differen ...

Issues with Google Fonts failing to load correctly

Would you mind taking a look at this issue for me? In all browsers except Firefox, the expected behavior is that a web font remains invisible until fully loaded, preserving space on the page. Interestingly, in Chrome and IE9 (the browsers I tested), ther ...

Ways to incorporate conditional logic with URL query parameters in Next.JS

I'm trying to implement conditional logic based on a URL query. In this scenario, I want to greet Kátia Fantes dynamically when she visits localhost:3000/katia-fantes. Any suggestions on how to achieve this? import { useRouter } from 'next/rou ...

Trouble with Displaying 3rd Level JQuery Dropdown Menu

Currently working on implementing a 3 level dropdown feature. I have been using a third-party responsive menu in Opencart and it's been working well. You can see a demo of it here: Unfortunately, Opencart does not natively support 3 level categories, ...

Can someone assist me with navigating through my SQL database?

Struggling with a script that searches multiple fields in the same table, I need it to return results even if one or three parameters are left blank. My attempts using PHP and MySql have been fruitless so far, which is why I am reaching out to the experts ...

FirebaseError encountered: Unable to update document due to absence of document. Updating document is only possible if document id is hard coded

For my latest project, I have a component that can successfully create a new user and add them to the database using the function createUserWithEmailAndPassword(auth, email, password). Now, I am working on another component that will allow users to edit t ...

What methods are available to gradually increase a counter until it reaches a specific number by a designated date?

I have a unique idea for my website - I want to create a special counter that gradually increases to a specific number, but does so over the course of an entire year. Imagine starting at 0 and aiming to reach 35340340 after exactly one year has passed. It ...

Using Symfony2 to make an Ajax request in order to show a message based on a particular condition

As a novice in the realm of JavaScript and Ajax, I am struggling to find a way to display a message based on certain conditions. Let's consider a scenario where a user can adjust the quantity of a product they wish to purchase. While implementing thi ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...

What is the best way to access an error's body in order to retrieve additional error message details when using the forge-api with nodejs?

I'm struggling to retrieve the body content when an error is returned from the API request. I've attempted creating a bucket with uppercase letters, but all I receive is an error object with statusCode = "400" and statusMessage = "BAD REQUEST". ...

Discovering the values within a separate JSON object

I have a collection of json objects that include information about different languages and user details. Languages User Details The user details contain a field for languages, which can have multiple values. Below is a sample json: $scope.languages = ...

Issue displaying numeric values in gridview template field

Looking to modify a gridview column setup that currently looks like this: <asp:TemplateField HeaderText="<%$ Resources:UserProfile, C_Updated %>" ItemStyle-Wrap="false" SortExpression="Updated"> <ItemTemplate> <asp:Literal ...