The following code works just fine without FriendlyUrls turned on for an ASP.Net Web Forms project:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '/Default.aspx/GetData',
type: 'POST',
beforeSend: function( xhr ) {
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
success: function (result) {
var resultData = (result.d? result.d : result);
alert(resultData);
},
error : function(){
alert('error');
}
});
});
</script>
Here is the server-side code for the page method (WebMethod):
[System.Web.Services.WebMethod]
public static string GetData()
{
return "Hello";
}
When I load the page in browser, I can see the response as { "d" : "Hello" }
, which is the expected result.
Now, if the friendly urls are added using the NuGet package Microsoft.AspNet.FriendlyUrls, the same code would not work. As FriendlyUrls are turned on, I changed the url in jquery ajax call to be "/Default/GetData", but then I would not receive the expected result. Rather I receive the html of the Default.aspx page.
I am struggling to find out why this would not work, the only thing I changed was adding the nuget package for the FriendlyUrls!
I have been trying to find solutions and the most close readable answers I could find were:
Using jQuery for AJAX with ASP.NET Webforms
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Note that all the related posts in given answers do not use FriendlyUrls. I have also seen some answers that indicate that the jquery ajax calls would work fine with MVC, WebAPI, but my project is restricted to use ASP.Net Web Forms.
Am I doing something wrong or missing something here? Has anyone encountered the same scenario for their project? If so, can you please answer how this can be solved? Thanks a bunch for taking time to read and reply.
So, ultimately I got the solution to my question by making following changes to my project:
Add FriednlyUrls to the project.
Remove the line in RegisterRoutes method that sets
settings.AutoRedirectMode
property in App_Start/RouteConfig.cs(note that setting it to RedirectMode.Permanent or RedirectMode.Off did NOT work for me)
Add authorization in web.config as follows under system.web section
Modify the url in ajax call set up to use Microsoft.AspNet.FriendlyUrls.Resolve function in order to get the correct url as below:
After spending way too much time on this, I found out that I needed to change this in App_Start/RouteConfig.cs: