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?