0

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?

Nestor
  • 8,194
  • 7
  • 77
  • 156

3 Answers3

1

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.

Community
  • 1
  • 1
Konamiman
  • 49,681
  • 17
  • 108
  • 138
  • WebClient looks good as well. Is there any WCF-like client for WebAPI? Like I create a client instance and call the methods "directly" by creating proxy classes and call their functions. – Nestor Sep 18 '15 at 08:09
  • I don' think so, see related discussion here: http://stackoverflow.com/questions/12968007/restful-web-service-auto-generate-wadl. I think that your best bet is to return your data as JSON, then use [JSON.NET](http://www.newtonsoft.com/json) or a similar tool for deserialization. – Konamiman Sep 18 '15 at 08:14
  • if you use OData in your WebAPI project, you can leverage the OData proxy generation: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-client-app otherwise, if writing the payloads manually is an option for you, you can always use the convenient Postman (https://www.getpostman.com/) – Fabio Salvalai Sep 18 '15 at 08:19
  • @FabioSalvalai The goal is to generate proxy classes to call various server-side functions. So, if a new server-side method appears, the generated proxy should contain the new function. – Nestor Sep 18 '15 at 08:25
  • Okay Nestor, I understand. That means of course that the generated proxy will only be updated at compile. With the help of T4 templates, this is precisely what the link above does, but it requires some meta data to understand how the proxy should be generated, such as choosing the right type, between int or string.Unfortunately, you will not be able to do such a thing if you just have a non-ODATA, RESTful API without a wadl description file, a swagger documentation, or other means to describe the details of your endpoints. – Fabio Salvalai Sep 18 '15 at 08:31
  • @FabioSalvalai So in my case, I can't create the proxies with the T4 as the WebAPI service is not an OData service in MVC 6, right? – Nestor Sep 18 '15 at 08:45
  • Perhaps with libraries like this one, if you are documenting your APIs with Swagger (just googled it, never tried it): https://github.com/enkafan/Swagger.WebApiProxy – Fabio Salvalai Sep 18 '15 at 08:49
  • Unfortunately it works with WebAPI 1 and 2 so I can't use with the new WebAPI 3. – Nestor Sep 18 '15 at 08:53
  • Maybe other libraries/api description formats provide alternatives which are better suited for you, I guess you'll have to google that a bit, but the concept is just that without providing Metadata you can't have a reliable proxy. – Fabio Salvalai Sep 18 '15 at 09:02
1

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.

Fabio Salvalai
  • 2,479
  • 17
  • 30
0

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.

alltej
  • 6,787
  • 10
  • 46
  • 87