Search code examples
c#asp.netajaxcross-site

Ajax call from apsx to code behind causes 500 error - Referrer Policy: strict-origin-when-cross-origin in .net


I would like to set a session variable in code behind so after received an ajax call result based on the result of that set a session variable.

This application is old webform and is not MVC Here is what I did Below is my Test.aspx

<asp:Button ID="cmdTest" runat="server" Text="Set session value"          
 OnClientClick="mytest();return false"/>

<Script>
    function myTest() {
        console.log("Document is ready.");
        $.ajax({
            type: "POST",
            url: "CheckBrowser.aspx/SetSessionVariable",
            data: JSON.stringify({ value: 'true' }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                // Handle the server's response (if needed)
                console.log("success");
            },
            error: function (error) {
                console.log("AJAX Error: " + error);
            }
        });
    }
</script>

this is my Test.aspx.cs code

[WebMethod(enableSession: true)]
public static void SetSessionVariable(string value)
{
    HttpContext.Current.Session["myTest"] = value;
    Debug.Print("session value set");
}

however I get Request URL: localhost:44310/Support/Test.aspx/SetSessionVariable Request Method: POST Status Code: 500 Remote Address: [::1]:44310 Referrer Policy: strict-origin-when-cross-origin see blow image of network trafic enter image description here This is strange as my origin is the same and i just from my aspx page perform an ajax call to set a variable in the same aspx code behind. I am not sure what i am missing any help will be much appreciated.


Solution

  • Thank you for all the explanation above today I figured out why this is happening. It is because I had made the SetSessionVariable method in code behind Protected. It should have been public. It is interesting. As I thought, js in aspx should have access to aspx.cs protected methods. I think I can close this question. Thanks for the follow-up