1

I get a 401 Unauthorized when my ajax is doing a POST event this is only when the project is being run through sitecore. This all works like a charm I need a work around for sitecore this is my current setup.

I followed Link 1 to setup my code, so I have the following:

MasterLayout.aspx:

<script src="jsfile.js" type="text/javascript"></script>

<script src="../../../content/javascript/jquery-1.6.2.min.js"></script>

MasterLayout.aspx.cs:

using System.Web.Services;

[WebMethod]
public static string GetDate()
{
   return DateTime.Now.ToString();
}

MyCharts.ascx

<div class="Result" id="Result">Click here for the time.</div>

jsfile.js:

$(document).ready(function() {
// Add the page method call as an onclick handler for the div.

    $('.Result').click(function() {
        $.ajax({
            type: "POST",
            url: "MyCharts.aspx/GetDate", // MyCharts.aspx is a logical page created in sitecore physically it loads MasterLayout with MyCharts within that.
            data: "{}",
            contentType: "application/json",
            dataType: "json",
            success: function(msg) {
                // Replace the div's content with the page method's return.
                $(".Result").text(msg.d);
            }
        });
    });
});

When debugging javascript tries to POST HelloWorld and I get:

"Message":"Authenticationfailed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"

Link 1: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Related Question: Getting "401 Unauthorized" error consistently with jquery call to webmethod

My Related Question: https://stackoverflow.com/questions/7837532/get-my-html-and-javascript-to-perform-postback-ajax-call

Community
  • 1
  • 1
Anicho
  • 2,647
  • 11
  • 48
  • 76
  • Does the `HelloWorld` WebMethod actually exist? I know that would cause a 404 not a 401 but your post isn't very clear as to which `WebMethod` you want to call – Simon Oct 21 '11 at 14:31
  • Edited code, it is GetDate I am getting not HelloWorld. – Anicho Oct 21 '11 at 15:48

3 Answers3

3

If this page is hosted in a Sitecore solution, which it seems like it is, the page request is probably going through the Sitecore context. You can edit the web.config to cause this page to not go through the Sitecore context. There's a setting called IgnoreUrlPrefixes:

<!--  IGNORE URLS
  Set IgnoreUrlPrefixes to a '|' separated list of url prefixes that should not be
  regarded and processed as friendly urls (ie. forms etc.)
-->
<setting name="IgnoreUrlPrefixes" value="{Pipe-delimited list}" />

You can update this list to include the path to your special page.

Mark Ursino
  • 31,209
  • 11
  • 51
  • 83
  • I have seen similar solutions to this, whilst researching over the weekend 1 upped since it can work. Although I needed the page to also be visible for sitecore. A potential solution would of been to load an .ashx page with http handlers that did all the work for me and then loaded the relevant result this page would be hidden from sitecore using IgnoreUrlPrefixes. – Anicho Oct 24 '11 at 07:57
2

A few nit-picks that may move you towards a solution:

  1. You don't need to include the "Data" property if you aren't passing any data
  2. You are using "POST" but you're not posting any data - use "GET" instead
  3. You say your contentType and dataTypes are JSON but the web method returns a string

The post/get may fix the problem - Get is much more lax with security than Post.

It may also help to add an error callback function to see if there is any more information as to why the request is failing.

jbabey
  • 45,965
  • 12
  • 71
  • 94
  • nope wasn't a miss click by me. I will eventually pass data, POST will eventually be true because I will be passing data user has selected. contentType and dataTypes incorrect yes this is true. – Anicho Oct 21 '11 at 16:11
  • 4
    I'm not sure where Anicho's authentication process is failing, but this answer isn't correct. When calling ASPX page methods, the request *must* be a POST with Content-Type `application/json`. Using GET or omitting the Content-Type will result in the entire page being returned instead of the static page method running and returning JSON. Even though the method returns a string, ASP.NET will automatically return this JSON from that method: `{"d":"Date String Here"}`. So, the dataType of `json` is also correct (though unnecessary with recent versions of jQuery). – Dave Ward Oct 22 '11 at 15:52
1

I wanted a solution that enabled me to allow the page I was doing the post on to be run through sitecores context. If you don't mind the page ignoring the context look at Mark Ursino answer it will work like a charm.

My answer does the following:

Javascript:

function MySuperCoolFunction() {
    strUser1 = document.getElementById("Symbol1").innerHTML;
    strUser2 = document.getElementById("Symbol2").innerHTML;

    var join = strUser1 + "," + strUser2;

    __doPostBack('upCurrencyCharts', join);
}

.ascx/.aspx:

<asp:UpdatePanel runat="server" ID="upCurrencyCharts" OnLoad="upCurrencyCharts_onload">
    <ContentTemplate>

           // My Content Here  

     </ContentTemplate> 
 </asp:UpdatePanel> 

.cs:

protected void upCurrencyCharts_onload(object sender, EventArgs e)
{
    string item1 = null;
    string item2 = null;

    if (IsPostBack)
    {      
       string items = Request["__EVENTARGUMENT"];
       string[] partsArray = items.Split(',');

            for (int i = 0; i < partsArray.Length; i++)
            {
                if (i == 0)
                {
                    item1 = partsArray[i];
                }

                if (i == 1)
                {
                    item2 = partsArray[i];
                }
            }
        }

        // do something with item1 and 2 here.. in mycase feed to database.

The javascript forces a postback event on my update panel, and parses a string of parameters I am sending through to the backend of my website. Onload event triggers on postback and fires anything I do in my onload event in this case puts the items into an array to split them and then puts them into a database. Simples. Thanks everyone for there help in this. :D

Anicho
  • 2,647
  • 11
  • 48
  • 76