Search code examples
jqueryasp.netajaxweb-servicesasmx

ajax webservice asmx 401 unauthorized error


I have an internal website that requires a login where people can record notes and other information during meetings. I am trying to post the data with an AJAX call to a webservice on the same server, in the same folder. I am getting an 401 unauthorized error.

Javascript:

function saveNotes()
{
    var json = "{ ID: 5, Note: 'Test Note'}";
    $.ajax({
        type: "POST",
        url: "AutoSaveService.asmx/AutoSave",
        data: json,
        xhrFields: { withCredentials: true },
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function (r) {
            var data = JSON.parse(r.d);
            console.log(data.M + ":" + data.N)
        },
        error: function (r) { console.log(r.responseText); },
        failure: function (r) { console.log(r.responseText); }
    });
}

WebService asmx file:

<%@ WebService Language="C#" Class="AutoSaveService" %>

[System.Web.Services.WebService(Namespace = "http://tempuri.org/")]
[System.Web.Services.WebServiceBinding(ConformsTo = System.Web.Services.WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoSaveService : System.Web.Services.WebService
{
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    public static string AutoSave(int ID, string Note)
    {
        var data = new { M = ID, N = Note };
        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

        return js.Serialize(data);
    }

}

I am using forms authentication (authenticating vs AD):

<authentication mode="Forms">
  <forms loginUrl="login.aspx" name="adAuthCookie" timeout="120" path="/"/>
</authentication>

I have never done ajax calls within a secure environment before, let me know what other information you need.

I've looked at other solutions to similar problems but can't get them to work.


Solution

  • I figured it out.

        public static string AutoSave(int ID, string Note)
    

    should be:

        public string AutoSave(int ID, string Note)