我正在尝试将对象从WebJob发布到MVC 4控制器。我正在使用实体框架。在控制器中,我无法正确绑定对象(参数为null)。我看了很多教程,看起来我的代码应该可行。
模型(这需要在EF的特定命名空间中才能找到它吗?):
public class CreateListingObject
{
public Listing listing;
public List<GalleryImage> images;
public CreateListingObject()
{
listing = new Listing();
images = new List<GalleryImage>();
}
}
public struct GalleryImage
{
public string picURL;
public string caption;
}
POST:
public void PostListing(CreateListingObject o)
{
Console.WriteLine("Posting listing: {0}", o.listing.Title);
HttpClient _httpClient = new HttpClient();
Uri uri = new Uri(_serviceUri, "/Automaton/CreateTestListing");
string json = BizbotHelper.SerializeJson(o);
HttpResponseMessage response = BizbotHelper.SendRequest(_httpClient, HttpMethod.Post, uri, json);
string r = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
}
SendRequest(感谢Azure搜索示例):
public static HttpResponseMessage SendRequest(HttpClient client, HttpMethod method, Uri uri, string json = null)
{
UriBuilder builder = new UriBuilder(uri);
//string separator = string.IsNullOrWhiteSpace(builder.Query) ? string.Empty : "&";
//builder.Query = builder.Query.TrimStart('?') + separator + ApiVersionString;
var request = new HttpRequestMessage(method, builder.Uri);
if (json != null)
{
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
return client.SendAsync(request).Result;
}
Controller Action片段(o这里是一个空对象):
[HttpPost]
public ActionResult CreateTestListing(CreateListingObject o)
{
Listing li = o.listing;
我已经确认,如果我使用相同的代码发布一个简单的对象,一切都按预期工作。
不是在PostListing中发送CreateListingObject,而是发送它:
var test = new
{
data = "hi mom"
};
并将我的操作更改为,然后参数被绑定并获得有效数据:
[HttpPost]
public ActionResult CreateTestListing(string data)
{
我还检查了WebJob中我的CreateListingObject的序列化,并且它完全按照我的预期填充。这让我怀疑我正在违反默认的ModelBinder。