📜 ⬆️ ⬇️

ASP.NET MVC - we "hide" Action

With the active use of the jQuery $ .ajax function in an ASP.NET MVC application, a problem may arise - the user may want to knock on the Action directly by entering the address in the browser line. On the one hand, there is nothing terrible in this, but the desire to “hide” the Action may arise. I propose such an easy way to solve such a problem, of course, without a claim to originality and mega-strikes :)

For example, an AJAX request like this

function saveItem(imgurl) {
$.ajax(
{
url: '<%=Url.Action("SaveItem") %>' ,
dataType: "json" ,
data: {
categoryid: $( "#categoryid" ).val(),
itemid: null ,
name: $( "#name" ).val()
},
success: function (data) { $( "div[id^=edititem]" ).html( '' ).hide(); getItems($( "#categoryid" ).val()); },
error: function (e) { alert(e.responseText); }
}
)
}

* This source code was highlighted with Source Code Highlighter .


calls the SaveItem method, which can be easily accessed from the browser string. To prevent this from happening, I use the following small ActionFilterAttribute:
')
public class AjaxFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext. HttpContext .Request.IsAjaxRequest())
{
filterContext.Result = new RedirectToRouteResult( "Error" ,
new RouteValueDictionary(
new
{
controller = "Home" ,
action = "Error"
}));
}

}
}

* This source code was highlighted with Source Code Highlighter .


Now it is enough for any method that returns an ActionResult to put down the [AjaxFilter] attribute, and the user who wants to call it directly will be distressed. Of course, you need to create a View Error.aspx and corresponding method in the Home controller (or where you will redirect)

Source: https://habr.com/ru/post/66491/


All Articles