11

A situation I ran across this week: we have a jQuery Ajax call that goes back to the server to get data

$.ajax(
{
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: fullMethodPath,
    data: data,
    dataType: "json",
    success: function(response) {
        successCallback(response);
    },
    error: errorCallback,
    complete: completeCallback
});

fullMethodPath is a link to a static method on a page (let's say /MyPage.aspx/MyMethod).

public partial class MyPage : Page
{
    // snip

    [WebMethod]
    public static AjaxData MyMethod(string param1, int param2)
    {
        // return some data here
    }
}

This works, no problem.

A colleague had attempted to replace this call with one where type was "GET". It broke, I had to fix it. Eventually, I went back to POST because we needed the fix quick, but it has been bugging me because semantically a GET is more "correct" in this case.

As I understand it, jQuery translates an object in data to a Query String: /MyPage.aspx/MyMethod?param1=value1&param2=value2 but all I could get back was the content of the page MyPage.aspx.

Is that just a "feature" of Page methods, or is there a way of making a GET request work?

pdr
  • 6,372
  • 1
  • 29
  • 38
  • What exactly is your problem? What do you mean with *but all I could get back was the content of the page MyPage.aspx.* ? Didn't the `GET` request work? – Felix Kling Mar 07 '10 at 18:56
  • @Felix: He means that he got the full contents of the page instead of calling the page method. – SLaks Mar 07 '10 at 19:07
  • @Felix: Have clarified what I meant by Page method – pdr Mar 07 '10 at 19:08

2 Answers2

28

For security reasons, ASP.Net AJAX page methods only support POST requests.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • I assume the security issue is that the method cannot be written to only accept one or the other? – pdr Mar 07 '10 at 19:10
  • I mean that because some methods should be limited to POST (because they're updating), it was easier to make it so that all methods are limited to POST, rather than implement a selective limiter like in MVC for ASP.NET. – pdr Mar 07 '10 at 19:22
  • @pdr: Actually, I believe the reason is to help prevent CSRF. – SLaks Mar 07 '10 at 19:40
  • This is one of the reasons I prefer ASP.NET MVC + REST: there's a clear guideline for GET vs POST and no additional technical restrictions imposed on it. – Craig Walker May 23 '10 at 16:12
1

It is true that ASP.NET AJAX page methods only support POST requests for security reasons but you can override this behavior by decorating your WebMethod with this these both attribute:

[WebMethod]
[ScriptMethod(UseHttpGet = true)]

I felt that the accepted answer was incomplete without pointing out a work around.

Jamshaid K.
  • 3,555
  • 1
  • 27
  • 42