0

i want to create a controller that has actions will responds only for ajax requests. i have tried the [ChildActionOnly] attribute but this stopped all ajax calls. So is there away to create a class with actions for ajax only?

secondly are there any precautions when creating such class?

Phill Greggan
  • 2,234
  • 3
  • 20
  • 33
  • 1
    You should create an `ApiController` for these tasks. http://www.davidhayden.me/blog/asp.net-mvc-4-web-api-routes-and-apicontroller – Ruslan Dec 06 '15 at 02:46
  • @Ruslan so there aren't anyways to block the call to an Ajax action from typing it on address bar from MVC restrictions? – Phill Greggan Dec 06 '15 at 02:48
  • 1
    @PhillGreggan There is. You need to restrict it to accept `POST` requests only, which can be done with an attribute `[HttpPost]` or a handful of similar ones. You will then also need to make sure that your *front-end* issues `POST` instead of `GET` AJAX calls. However, while this will definitely prevent the user from typing it in their browser, there are other ways to fake `POST` requests using more sophisticated tools, if the user is tech-savvy and very determined. – Ruslan Dec 06 '15 at 02:50

1 Answers1

1

To talk about the problem you have there is no direct method/attribute which can only respond to ajax request only.However you can create your own attribute which will respond to ajax request.

In MVC ajax request can be intercepted with Request.IsAjaxRequest()

Here is a code snippet:

public class isAjaxAttribute : ActionMethodSelectorAttribute 
{
    public override bool IsValidRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest();
    }
}

Now you can use this attribute on your controller method like

[isAjax]
public ActionResult ajaxMethod()
{

}