ASP.NET (cookieless) web method returns 401 Authentication failed

I had application with cookieless session. This was the reason why I was getting ‘401 Authentication failed’ error.

Something like this would not work

function LoadDealersData() {
        var url = "/Default.aspx/GetDealers";
	$.ajax({
		type: "GET",
		url: url,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: '{ pid:' + currentProvince + '}',
		error: function (data, exception) {

		},
		success: function (response) {
			// do stuff with reponse.d
		},
		complete: function () {

		}
	});
}

Code behind:

[Webmethod]
public static List<Dealer> GetDealers(int pid)
{
	...
	return dealers;
}

Solution was to use generic handler (.ashx)

public List<Dealer> GetDealers()
{
	try
	{
		int pid = Convert.ToInt32(Request["pid"]);
		List<Dealers> dealers = new List<Dealers>();
		//...
		Response.ReturnJSON(new
		{
			dealers = dealers
		});
	}
	catch()
	return null;
}

public static void ReturnJSON(this HttpResponse response, object data)
{
	response.Clear();
	response.ContentType = "application/json";;
	response.Expires = 0;
	response.Write(new JavaScriptSerializer().Serialize(data));
	response.End();
}

Modified JavaScript

function LoadDealersData() {
	var url = "/SomeLocationWhereHandlerIs/MyHandler.ashx";
	$.ajax({
		type: "GET",
		url: url,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: data: 'whattodo=getDealers&pid=' + currentProvince,
		error: function (data, exception) {

		},
		success: function (response) {
			// do stuff with response.dealers; 
			// response.dealers becuase we are returning dealers variable in code behind
		},
		complete: function () {

		}
	});
}

Leave a Reply

Your email address will not be published. Required fields are marked *