Refactoring my experiment which yielded 7 + 13 + 22 = 42, I introduce a data transfer object in lieu of serializing anonymous types:
namespace Learning.Models
{
public class CornyThing
{
public int Foo { get; set; }
public int Bar { get; set; }
public int Composition { get; set; }
public string Explanation { get; set; }
}
}
The Web API Controller gets trimmed way down...
using System.Web.Http;
using Learning.Models;
namespace Learning.Controllers
{
public class ExperimentController : ApiController
{
public CornyThing Put(int id, [FromBody]CornyThing value)
{
value.Composition = id + value.Foo + value.Bar;
value.Explanation = id + " + " + value.Foo + " + " + value.Bar + " = " +
value.Composition;
return value;
}
}
}
Finally, you may see below that I am talking to the Controller above at a domain name as suggested below. If I put a copy of the code base to IIS8 Express and then run the code below from Cassini I am able to make it all work as both sides understand what the CornyThing object is. I can also imagine how this sort of sharing could be painful and come with maintenance overhead. Hmmmm.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Mvc;
using Learning.Models;
namespace Learning.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
string status;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://www.dummygunk.com/");
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
CornyThing whatever = new CornyThing() { Foo = 13, Bar = 22 };
var response = client.PutAsJsonAsync("api/experiment/7", whatever).Result;
if (response.IsSuccessStatusCode)
{
CornyThing dto = response.Content.ReadAsAsync<CornyThing>().Result;
status = dto.Explanation;
} else {
status = "Fail!";
}
ViewBag.Status = status;
return View();
}
}
}
No comments:
Post a Comment