Nestor
Nestor

Reputation: 8384

How to create .Net client for MVC 6 WebAPI

The new MVC 6 already includes the new WebAPI (WebAPI 3?) so you can easily create a WebAPI service and access the data via the proper URL.

I use the latest beta to create a default WebAPI service but couldn't find tutorials of how to access the data the URLs with a .Net client.

I checked how to create a client for WebAPI 2 and used this code:

The controller

    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET: api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }
   }

The client:

        public async Task<string> GetData()
        {
            string result= "none";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:55792/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // New code:
                HttpResponseMessage response = await client.GetAsync("api/values/1");
                if (response.IsSuccessStatusCode)
                {
                    result = await response.Content.ReadAsStringAsync();
                    return result;
                }
            }
            return result;
        }

I has received the string, so it works but I'm not convinced if it is the recommended way for WebAPI access in MVC 6.

What approach would you recommend?

Upvotes: 0

Views: 2638

Answers (3)

alltej
alltej

Reputation: 7285

I use HttpClient because of async features on .NET 4.5+ environments. HttpClient is newer and was created to support the growing needs of API Rest calls.

Upvotes: 0

Fabio Salvalai
Fabio Salvalai

Reputation: 2509

For the server, whether it is MVC 6 or any other version, it doesn't matter at all how you call it. WebAPIs are designed to be inter-operable and you can consume it how it suits you. As a matter of fact, you can even consume it with completely different languages, such as Python or JavaScript. Your code sample is therefore, absolutely fine.

Now, since you are developing your client in .Net, and as it seems you are developing a RESTful API, I would personally not use the HttpClient, nor WebClient, but I would rely on a popular, highly maintained third party open-source NuGet package, such as RestSharp.

The reason for this is not because it makes a better job, but just because the required code looks cleaner, you will have to put less efforts to read the responses, deserialize JSON payloads, etc. Also, the classes are designed to embrace the REST philosophy instead of just sending raw HTTP requests.

Upvotes: 1

Konamiman
Konamiman

Reputation: 50273

The WebClient class is generally considered a better alternative than HttpClient, as it is simpler and easier to use (despite handling character encodings the completely wrong way). But if the HttpClient class works for you, go ahead and use it.

Upvotes: 1

Related Questions