2

I have an HTTP Post controller that I use in a SharePoint online provider hosted app.

The controller code:

    [HttpPost]
    public JsonResult FinaliseQuote(string quote)
    {
    using (unitOfWorks)
     {
          User spUser = null;
           ClientContext context = GetClientContext();
           context.Web.CurrentUser;

           context.Load(spUser, user => user.Title);
           context.ExecuteQuery();

            var finalisedQuote = JsonConvert.DeserializeObject<FinalisedQuote>(System.Uri.UnescapeDataString(quote));

            var convertedQuote = finalisedQuote.Save(unitOfWorks, context);
 }

}

in my GenericController I have the following method:

   protected ClientContext GetClientContext()
    {
        ClientContext context = null;
        context = (ClientContext)HttpContext.Session["clientContext"];

        if (context == null)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
            if (spContext != null)
            {
                context = spContext.CreateUserClientContextForSPHost();
                HttpContext.Session.Add("clientContext", context);
            }
        }

        if (context == null)
            throw new Exception("Client Context is Null");            

        return context;
    }

So basically I am saving the Client Context to the HTTP Session, and retrieving it via the AJAX POST method.

The problem is when the httpcontext times out. I have no way of getting the context in the POST ajax call.

How do you normally retrieve the sharepoint clientcontext from a ajax HTTP Post call?

2

I had a similar problem as you, with a null SharePointContext object.

For me I was using the SharePointContextFilter Attribute on the Action method, and wrapping the ClientContext inside a using statement.

[HttpPost]
[SharePointContextFilter]
public ActionResult FinaliseQuote(string quote)
{
    var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);

    using (var clientContext = spContext.CreateUserClientContextForSPHost())
    {
        .... your code
    }
}

In my code I return an ActionResult, but you can most likely change this to a JsonResult as per your method without issue.

In your javascript you need to make sure to include the SPHostUrl in the query string of your request.

Since you haven't included any javascript code that you are using, I will give an example(untested)

var spHostUrl = getSPHostUrlFromQueryString(window.location.search);

jQuery.ajax({
    url: '@Url.Action("FinaliseQuote", "Home")?spHostUrl=' + spHostUrl,
    type: "POST",
    data:
        "{'quote': '12345ABCDE'}",
    headers: {
        "accept": "application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: function (d) { console.log(d); },
    error: function () { console.log('fail'); }
});

/*
Note this method is taken from 
http://www.sharepoint-reference.com/Blog/Code%20Samples/spcontext.js.txt

it is a helper library which you should probably read into
*/
// Gets SPHostUrl from the given query string.
function getSPHostUrlFromQueryString(queryString) {
    if (queryString) {
        if (queryString[0] === "?") {
            queryString = queryString.substring(1);
        }

        var keyValuePairArray = queryString.split("&");

        for (var i = 0; i < keyValuePairArray.length; i++) {
            var currentKeyValuePair = keyValuePairArray[i].split("=");

            if (currentKeyValuePair.length > 1 && currentKeyValuePair[0] == SPHostUrlKey) {
                return currentKeyValuePair[1];
            }
        }
    }

    return null;
}

As mentioned in the comments above the getSPHostUrlFromQueryString method, the code is taken from http://www.sharepoint-reference.com/Blog/Code%20Samples/spcontext.js.txt

This has resolved the problem for me, hopefully will help you too.

Note, you title says HTTP GET, but your code is a POST, so I assume you mean HTTP POST?

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.