1

I need to block direct access of action method by web browser. However I want to invoke the actions through ajax call.

The following code does the job for me

public ActionResult DashBoard()
{
    if (Request.IsAjaxRequest())
    {
        return View();
    }
    else
    {
        return RedirectToAction("Index");
    }
}

However writing if else block in every action method is hectic thing to do and there must be better way to handle it globally.

Muhammed Shevil KP
  • 1,404
  • 1
  • 16
  • 21
Anuj Tamrakar
  • 251
  • 2
  • 13
  • 5
    Create an action filter and apply it globally - refer [this answer](http://stackoverflow.com/questions/23900411/mvc-set-accessibility-level-on-a-method-called-from-ajax/23900475#23900475) for an example (in that case it returns a 404 if not an ajax request –  Apr 23 '17 at 06:48
  • Thanks, I did implement it globally too. However I don't want the filter on on my home page. How do i exclude this filter in specific Action Method – Anuj Tamrakar Apr 23 '17 at 08:57
  • In that case, consider a BaseController and apply the filter to that controller. Then have all your controllers except HomeController inherit from BaseController. Another option is to register your filters using a `IFilterProvider` (refer [this answer](http://stackoverflow.com/questions/28193082/prevent-a-asp-net-mvc-global-filter-from-being-applied-on-elmah-action) for an example) –  Apr 23 '17 at 09:04
  • Thanks, It worked :) – Anuj Tamrakar Apr 23 '17 at 09:10

0 Answers0