Search code examples
c#angularjswebmethod

$http GET returns complete HTML source


I am trying to use $http to send a get request to my server. I have a webmethod that looks like this:

[WebMethod]
[ScriptMethod(UseHttpGet = true,
ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public static IList<EmailContentModel> GetEmailContents(int emailTemplateID, int? pageIndex, int? pageSize)
{
    var clientManagementRepository = GetClientManagementRepository();
    var emailContents = clientManagementRepository.GetEmailContents(emailTemplateID, pageIndex, pageSize);
    return emailContents;
}

When I use POST method (and change the webmethod to UseHttpGet = false) the following returns the correct data.

function getEmailContentDetails(pageIndex) {
    return $http({
    method: "POST",
    url: "EmailContent.aspx/GetEmailContents",
    data: JSON.stringify({ emailTemplateID: emailTemplateID, pageIndex: pageIndex, pageSize: pageSize }),
    headers: { 'Content-Type': "application/json; charset=utf-8" }
    }).then(onSuccess, onError);
}

But when I use the GET method

function getEmailContentDetails(pageIndex) {
    return $http({
    method: "GET",
    url: "EmailContent.aspx/GetEmailContents",
    params: { emailTemplateID: 3, pageIndex: 1, pageSize: 10 }
    headers: { 'Content-Type': "application/json; charset=utf-8" }
    }).then(onSuccess, onError);     
}

It falls over and returns the complete HTML source of the page to me instead of the correct data. I have looked with SQL profiler and the DB is not even being hit with a request when I use GET. When I use ajax, I can use GET and it works fine.


Solution

  • So, angular does not send the 'Content-Type' if there is no data attribute on the call to $http. This is why I was getting HTML back. The solution was to add an empty data attribute.

    function getEmailContentDetails(pageIndex) {
        return $http({
        method: "GET",
        url: "EmailContent.aspx/GetEmailContents",
        params: bbparams,
        data: '',  <--TAA DAA
        headers: {
            'Content-Type': "application/json; charset=utf-8"
        }
        }).then(onSuccess, onError);
    }