简体   繁体   中英

401:unauthorized when I try to call a method via AJAX in .net

I have a .net project in the framework 4.5.1

When I use ajax like below, it works and the debugger hits the page_load event:

$.ajax({
        "async": true,
        "crossDomain": true,
        type: "POST",
        url: "Advanced.aspx",
        contentType: "application/json; charset=utf-8",
        success: function (ms) {
            alert('success');
        }
    })

In my advanced.aspx.cs , I have the method below:

[System.Web.Services.WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
        public static string SaveChange(string myval)
        {
            //dummy code for test purposes.
            string u = myval + "X";
            return u;
        }

I want to hit this method via ajax . To do this, I am updating my ajax call like below:

$.ajax({
            "async": true,
            "crossDomain": true,
            type: "POST",
            url: "Advanced.aspx/SaveChange",
            data: {username:"test"},
            contentType: "application/json; charset=utf-8",
            success: function (ms) {
                alert('success');
            }
        })

However, it gives me 401:unauthorized error when i do it in that way, shown below:

在此处输入图片说明

How can I fix this? Tried lots of things for the last few hours, no luck.. Any help would be appreciated.

EDIT: I've used async and crossDomain hoping to fix this issue, didn't help. Normally they don't exist in my ajax call, nothing changes.

Try updating your AJAX JS to:

$.ajax({
    type: "POST",
    url: "Advanced.aspx/SaveChange",
    data: {myval:"test"},
    success: function (ms) {
        alert('success');
    }
})

Found the answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"

I have used settings.AutoRedirectMode = RedirectMode.Off; instead of RedirectMode.Permanent in ~/App_Start/RouteConfig.cs , which fixed the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM