3

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.

Community
  • 1
  • 1
cost
  • 4,420
  • 8
  • 48
  • 80
  • possible duplicate of [ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"](http://stackoverflow.com/questions/23033614/asp-net-calling-webmethod-with-jquery-ajax-401-unauthorized) – Ohgodwhy May 16 '14 at 12:37
  • 1
    @Ohgodwhy it's not the same question, it's the one that suggested I should turn off Redirecting off, and the piece it mentions about 'use this if you use friendly urls' doesn't work. I want a solution that lets me keep `RedirectMode` on – cost May 16 '14 at 17:18

1 Answers1

6

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.

Ronald Palmer
  • 111
  • 1
  • 7