Ali
Ali

Reputation: 2768

Handle Authentication in AJAX Calls

I am using the following code in my controller

[HttpPost]
public ActionResult SearchResultsAll(string keyword)
{
 System.Threading.Thread.Sleep(1000);
 string data = "Search results for " + keyword;
 return Json(data, JsonRequestBehavior.AllowGet);
}

and trying an AJAX call as following

$.ajax({
url: "/Home/SearchResultsAll",
type: 'POST',
data: {
 keyword: searchString                        
},
  success: function (data) {
  console.log(data);
  },
  error: function (jqXHR) { 
  console.log("ERROR");},
  complete: function (jqXHR, status) { 
  console.log("DONE"); 
  }
});

Instead of getting the string back, I get the HTML code for my login page - Yes the authentication is active on my HomeController

How do I tackle this in AJAX calls?

Upvotes: 1

Views: 47

Answers (1)

hamed hossani
hamed hossani

Reputation: 1002

The problem with applying Authorize globally is that you have to be logged on (authorized) before you can log on or register.

[HttpPost]
[AllowAnonymous]
public ActionResult SearchResultsAll(string keyword)
{
 System.Threading.Thread.Sleep(1000);
 string data = "Search results for " + keyword;
 return Json(data, JsonRequestBehavior.AllowGet);
}

AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to certain controller actions, like the login and register Actions

Upvotes: 3

Related Questions