I have a piece of jquery that makes an ajax call to a server side webmethod
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "TestPage.aspx/TestString",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
This works fine if I have routing turned off
settings.AutoRedirectMode = RedirectMode.Off;
I'd like to have it on, but when I do, the ajax call fails with “401 (Unauthorized).” Is there a way I can make my ajax calls while still having routing on?
settings.AutoRedirectMode = RedirectMode.Permanent;
Edit: Some people have voted that this should be closed as a duplicate and that the answer is over here, but that answer doesn't help. The first solution it offers is to set RedirectMode to Off, which is exactly what I don't want to do, and the other bit about Friendly Urls doesn't work.
I can see your issue - disabling AutoRedirectMode means .aspx URLs are freely accessible (not good). But you want your WebMethod accessible using the ASPX url.
A work around to this is to disable auto redirect mode as shown above
settings.AutoRedirectMode = RedirectMode.Off;
And handle requests containing .aspx pages yourself in the page_load (not called when hitting your WebMethod).
protected void Page_Load(object sender, EventArgs e)
{
if(Request.RawUrl.Contains(".aspx"))
{
Response.StatusCode = 404;
Server.Transfer("page-not-found.aspx");
}
}
If you want to redirect as per normal instead of sending a 404 - strip the .ASPX and send a 301 using :
Response.RedirectPermanent(Request.RawUrl.Replace(".aspx",""));
If you use a MasterPage or inherit from page you'll only need to write the code once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With