Search code examples
asp.net-mvcjqueryjquery-dialogunauthorized

Authorization and Jquery dialog problem


I have a little problem with a Jquery dialog for an action that requires a role. In my example, the user can click on a delete button and must confirm the action. In my controller, the Delete action requires a role, if the user is in the required role, the object is deleted.

The problem: How to alert the user if * the element was deleted (redirect to the Index view) * there was an error (alert with the message) * he doesn't have the rights to delete (alert with the message)

Before using the authorize filter, the delete action returned a JSON with a Boolean that indicates if there was an error, an URL to redirect on success and a message to alert on error.

As I can't return a JSON from my filter, I created an other method with the authorize filter that returns a partial view with the confirm content. If the user doesn't have the rights, the filter returns a partial view with an unauthorized exception content.

The problem: How to distinct which partial view was returned. When I create the dialog, I need to know for the buttons function.

Thanks!


Solution

  • Found a solution by adding code to the Global.asax:

    protected void Application_EndRequest()
        {
            if (Context.Response.StatusCode == 302 &&
                Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                Context.Response.Clear();
                Context.Response.StatusCode = 401;
            }
        }