Pages

Wednesday, February 17, 2016

How to post the array of guids to the intranet

I thought that sending a bunch of guid to the server should be a trivial task. And from the client side it really is. Slightly harder if you want to build a small helper utility for that...

So the conditions of the problem. We have a Asp.Net web-application, running on the IIS server somewhere in the local network. All the methods are required a domain user authentication. It has a method that accepts posts like:

[HttpPost]
public void ReceiveContactIds(Guid[] contactIds) { ... }

There are a lot of possible solutions, after a quick googling I came got that stackoverflow answer.
Lets use the HttpClient solution! Yep... Unfortunately, it didn't helped as it is. First of all - how to send an array to the method and secondly it has no mention of the authentication process.

But those problems can be solved! That answer was not that helpful, but that one is much better. And we can use DefaultCredentials for current user. As for arrays - I just reused my experience with JavaScript and decided to send a StringContent with JSON. Here is my solution:

    private static void SendContactIds(IEnumerable<Guid> contactIds)
    {
        var credentials = CredentialCache.DefaultCredentials;
        var handler = new HttpClientHandler { Credentials = credentials };

        using (var client = new HttpClient(handler))
        {
            var content = new StringContent(
                     JsonConvert.SerializeObject(new { contactIds }),
                     UnicodeEncoding.UTF8,
                     "application/json");

            var action = "http://intranet.local/ReceiveContactIds";

            var result = client.PostAsync(action, content).Result;
            result.EnsureSuccessStatusCode();
        }
    }

No comments:

Post a Comment