解决了!检查帖子底部的解决方案。
所以我有一个我正在开发的 web api,它的工作非常好,帖子对于只包含基本类型的简单类型非常有用。一个有效的例子:
public class Investigator
{
public int InvestigatorId { get; set; }
public string Name { get; set; }
}
但是,对于嵌套类型,嵌套对象会作为其默认表示形式返回(0 和空值取决于类型)。这是一个不起作用的示例:
public class Project
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public virtual State State { get; set; }
public string City { get; set; }
public virtual Investigator ProjectInvestigator { get; set; }
}
当我调用 uri 来发布项目时,所有字段都可以正常通过,除了嵌套类型,它们以其默认表示形式返回(调查员返回 0 表示 id,null 表示名称)。如果我在发布请求中不包括调查员,则调查员对象本身作为 null 而不是默认对象通过。所以我知道它至少被代码看到了,但是它没有正确反序列化或其他东西。什么可能导致这种情况,我可以在哪里查看在反序列化之前输入的数据?
其他可能相关的代码部分是控制器:
public class ProjectsController : ApiController
{
private NovascotiaContext db = new NovascotiaContext();
protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
db.Configuration.ProxyCreationEnabled = false;
}
// GET api/Projects
public IEnumerable<Project> GetProjects()
{
return db.Projects.AsEnumerable();
}
// GET api/Projects/5
public Project GetProject(int id)
{
Project project = db.Projects.Find(id);
if (project == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return project;
}
// PUT api/Projects/5
public HttpResponseMessage PutProject(int id, Project project)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
if (id != project.ProjectId)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
db.Entry(project).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
// POST api/Projects
public HttpResponseMessage PostProject([FromBody]Project project)
{
if (ModelState.IsValid)
{
db.Projects.Add(project);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, project);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = project.ProjectId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
// DELETE api/Projects/5
public HttpResponseMessage DeleteProject(int id)
{
Project project = db.Projects.Find(id);
if (project == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Projects.Remove(project);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK, project);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
和 web api 配置:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
}
编辑:通过 HTTPService 类在 as3/flex 中完成发布请求:
var p:Project = new Project();
p.City = "ACity";
p.ProjectName = "AProjectName";
var state:data.State = new data.State();
state.StateId = 98;
state.StateName = "Tennessee";
p.State = state;
var investigator:Investigator = new Investigator();
investigator.InvestigatorId = 1;
investigator.Name = "John Doe";
p.ProjectInvestigator = investigator;
projectPostService.send(p);
其中 projectPostService 是一个带有 method="POST" 的 HTTPService 对象。奇怪的是,在写这篇文章的时候,我创建了一个简单的页面来访问服务并且它成功了,所以这显然是 as3/flex 和 web api 之间的通信。这是有效的页面:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert("ready");
var project = {
"ProjectId": 2,
"ProjectName": "Aprojectname",
"State": { "StateId": 98, "StateName": "Tennessee" },
"ProjectInvestigator": { "InvestigatorId": 1, "Name": "John Doe" }
};
$.ajax({
url: "http://localhost/api/Projects",
type: 'POST',
dataType: 'json',
data: project,
success: function (data) {
alert(JSON.stringify(data));
},
failure: function (data) {
alert('fail');
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
编辑标题以匹配更具体的问题。如果有人有任何在 as3/flex 和 web api 项目之间工作的经验,任何帮助将不胜感激。
另一个编辑:似乎 HTTPService 类遍历要发送的对象上的每个属性,并将其转换为名称/值对。这适用于“0 深度”字段,但对于嵌套对象,字段类似于“字段”:“[对象对象]”。
解决方案:我最终在 as3 中使用 URLLoader 来访问服务 url。有一段时间我没有成功发布嵌套对象,因为嵌套类型一直为空。我的解决方案是将内容类型设置为文本,这是我之前忽略的。对于遇到此问题的其他任何人,要使用上述服务,这是一个示例:
var p:Project = new Project();
p.City = "ACity";
p.ProjectName = "AProjectName";
var state:data.State = new data.State();
state.StateId = 98;
state.StateName = "Tennessee";
p.State = state;
var investigator:Investigator = new Investigator();
investigator.InvestigatorId = 1;
investigator.Name = "John Doe";
p.ProjectInvestigator = investigator;
var loader:URLLoader = new URLLoader();
var hdr:URLRequestHeader = new URLRequestHeader("Content-Type", "application/json");
var request:URLRequest = new URLRequest("http://localhost/api/Projects");
request.requestHeaders.push(hdr);
request.data = com.adobe.serialization.json.JSON.encode(p);
request.contentType = "TEXT";
request.method = "POST";
loader.addEventListener(Event.COMPLETE, function(e:Event):void{
trace(loader.data); //return
});
loader.load(request);