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

What is the best way to prevent a directory from being included in the Webpack bundle?

Issue: Despite configuring my Webpack settings in webpack.config.js to exclude files from the ./src/Portfolio directory, all files are being bundled by Webpack. Code Snippet: Webpack.config.js const path = require('path'); module.exports = { ...

Is it possible to submit a form using AJAX in WordPress without relying on WordPress functions?

As I work on constructing a website using Wordpress, I am encountering an issue with submitting a form via ajax. I'm wondering if it's possible to achieve this without relying on Wordpress functions. Currently, my code runs without errors and dis ...

Enable the ability to scroll and click to navigate an overlapping Div element

A customer has a website with a dark teal design and is not pleased with the appearance of the scroll bar, as it disrupts the overall style. The client requested that I find a solution without using third-party libraries, and one that they can easily under ...

Encountering 'Illegal Invocation' error while running a basic script

Exploring the Speech Recognition API has been on my to-do list, so I decided to create a simple page that initiates recognition when clicking on the body element. Here is a snippet from my scripts.js file: var recognition = new window.webkitSpeechRecognit ...

Creating Visual Organizational Charts with Open Source Software

Can anyone recommend any free or open source tools for designing organizational charts? ...

Issues with functionality arise when cloning HTML divs using JQuery

VIDEO I created a feature where clicking a button allows users to duplicate a note div. However, the copied note does not function like the original - it's not draggable and changing the color of the copied note affects the original note's color. ...

Tips for Uploading the Contents from 2 Select Boxes

In my ASP.NET MVC application, I have two list boxes named #AvailableItems and #AssignedItems. I am able to transfer items from one box to the other. Additionally, there are related values stored as attributes on the Save link that also need to be submitt ...

Utilizing Selenium RemoteWebDriver with a Windows Service for running ChromeDriver

Background: Operating System: Windows 10 Home; Development Tool: Visual Studio 2015 Community; Programming Language: C#; NSSM; ChromeDriver Version: 2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129); Selenium WebDriver Package: 2.53.1; Ch ...

Having trouble getting card animations to slide down using React Spring

I am currently learning React and attempting to create a slide-down animation for my div element using react-spring. However, I am facing an issue where the slide-down effect is not functioning as expected even though I followed a tutorial for implementati ...

Leveraging PHP, AJAX, and MySQL within the CodeIgniter framework

I am currently venturing into the world of web development using the codeigniter PHP framework. My current hurdle involves a select dropdown on a page, populated with unique IDs such as 1, 2, 3 from the database. What I aim to achieve is, when a value is s ...

Creating an autocomplete feature with just one input field to display information for two to three additional input fields

I'm working on implementing an autocomplete feature similar to this example: . Feel free to test it out with the code snippets provided: 1000, 1001. I've successfully implemented the autocomplete functionality where typing in Pa suggests Paris. ...

Guide on how to compile template strings during the build process with Babel, without using Webpack

I'm currently utilizing Babel for transpiling some ES6 code, excluding Webpack. Within the code, there is a template literal that I wish to evaluate during the build process. The import in the code where I want to inject the version looks like this: ...

Here's a guide on how to display texts underneath icons in Buttons using Material UI

Currently, this is the Button I have displayed I am trying to figure out how to position the Dummy Button text beneath the icon. Can someone assist me with this? Below is my code snippet: <Button className={classes.dummyButton}> <Image src ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

Utilizing Sequelize to Convert and Cast Data in iLike Queries

When using Sequelize for a full-text search, I encountered an issue with applying the iLike operator to columns of INTEGER or DATE type. How can I cast off a column in this case? To illustrate, here is an example of what I am trying to achieve with a Post ...

When using DataContractJsonSerializer, you can deserialize an object that may either be a string or an object

Currently, I am fetching data from an API that sends me an array. The "params" object is a string in the first element and an object in the second one. Here is how my DataContract looks: [DataMember(Name = "params")] string Params; [DataMember(Name = "p ...

Troubleshooting Problem with ListItem Alignment in Material UI v0 involving Custom Avatar Component

Material UI version: v0.20.0 I'm facing an issue with aligning the leftAvatar value using the CustomAvatar component, as shown in the attached screenshot. Any assistance would be appreciated. CustomAvatar: The functionality of this component is cond ...

Automatically redirect users on page refresh using jQuery

I am attempting to use jQuery to detect when the user refreshes the page in order to redirect, but I can't seem to get it working. Can someone help me figure out what is wrong with this code? <?php include 'instagram.php'; ?> <! ...

Enhancing the appearance of individual cells within an HTML table by applying custom classes

I'm in the process of automating report generation for my organization. Our workflow involves using R to summarize data from Excel, then utilizing Rmarkdown, knitr, and the "htmlTable" package to generate HTML files. Currently, I am implementing CSS ...

Creating virtual hover effects on Android browsers for touch events

My Wordpress website is currently utilizing Superfish 1.5.4 to display menu items. The menu on my site includes several main menu items, which are clickable pages, and hovering over these main items should reveal sub-menu options. When I hover over a mai ...