I have a simple Azure Worker Role in which I want to host Web API. I would like to setup the Web API controllers so that I can access them same way as a jQuery post so that I don't have to create shell classes and my Web API can remain flexible for use with jQuery in the future.
Q: How can I post from a C# client to a self hosted Web API controller in a worker role, without using shell classes?
I've worked with Web API in the past where it's hosted in a regular ASP.NET project and I am able to access it via jQuery doing something like this:
//Web API Controller
public class TestController : ApiController
{
public void Post(string item, string action)
{
//...
}
}
//jQuery
$.post("/api/test/", { item: "myItem", action: "someAction" }, function (data)
{
//...
}
For my worker role project, I followed the instructions on ASP.NET for Host ASP.NET Web API 2 in an Azure Worker Role and set up WebAPI. I'd like to be able to access the controller the same way from a C# client. However, the documentation on ASP.NET for Calling a Web API from a .NET Client uses classes, rather than individual variables. The code samples end up looking something like below. Edit: I have been able to successfully use this method to communicate data to the worker role.
//Shell Object
public class ShellObject
{
public string item;
public string action
}
//Web API Controller
public class TestController : ApiController
{
public void Post(ShellObject shellObject)
{
//Unpack object, then do action
//...
}
}
//C# Client
ShellObject shellObject = new ShellObject() { item = "myItem", action = "someAction" }
var response = await client.PostAsync("api/test/", shellObject);
Because I don't want to create unnecessary shell classes in multiple places in my code, I'd like to do something like below. Doing it this way also keeps my Web API flexible so that it can be used from a web based jQuery project in the future (which in my case is a very possible scenario). However, these methods doesn't work; the server returns a "Method Not Allowed" or the post just hangs. Additionally, the posts don't seem to be showing up in Fiddler. Edit: Additionally, because this is intended to be a general purpose server, it's possible for the Worker Role and the calling C# client to be in different solution, so that they cannot share class definitions. Additionally, serializing to JSON before the post is fine, as long as there isn't a need for shell classes.
//Web API Controller
public class TestController : ApiController
{
public void Post(string item, string action)
{
//...
}
}
//Simple Post
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["item"] = "myItem";
data["action"] = "myAction";
var response = wb.UploadValues("http://workerroleaddress/api/test/", "POST", data);
}
Q: How can I post from a C# client to a self hosted Web API controller in a worker role, without using shell classes?