我正在使用MVC3编写一个Web应用程序但是当试图将一个对象传递给控制器并显示它时,它似乎无法识别类型或其他东西.
我有一个Job对象,JobService返回一个这样的Job:
public Job View(int jobId)
{
Job job=_jobRepository.Jobs.Where(x => x.Id == jobId).FirstOrDefault();
return job;
}
在WebService中我调用View如下:
[WebMethod]
public Job GetJob(GetJobRequest getJobRequest)
{
var getJobResponse = new GetJobResponse();
getJobResponse.Job = _jobService.View(getJobRequest.Id);
return getJobResponse.Job;
}
然后控制器调用:
public class JobsController : Controller
{
public ActionResult Index()
{
var jobModel = new JobModel();
using (var webServiceSoapClient = new WebServiceSoapClient())
{
var getJobRequest = new GetJobRequest();
getJobRequest.Id = 26038;
jobModel.Job = webServiceSoapClient.GetJob(getJobRequest);
}
return View(jobModel);
}
}
并且它抛出了这个错误:
System.Web.Services.Protocols.SoapException: Server was unable to process request. —> System.InvalidOperationException: There was an error generating the XML document. —> System.InvalidOperationException: The type System.Data.Entity.DynamicProxies.Job_55765AEC3BD02AFD7E0527408ED5746E1054965A59B82A127B5A688C19C61D5B was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write9_Job(String n, String ns, Job o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write18_GetJobResponse(Object[] p)
at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer13.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
— End of inner exception stack trace —
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Web.Services.Protocols.SoapServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
at System.Web.Services.Protocols.WebServiceHandler.Invoke()
— End of inner exception stack trace —
起初我正在将GetJobResponse传递给该服务,但我试图让它尽可能简单,以使其正常工作,我仍然无法弄明白.我已经看到有其他问题建议使用XmlInclude和东西,但它仍然无法正常工作.
应用于此:
public string SerializeObjectToXMLString(object theObject)
{
// Exceptions are handled by the caller
using (System.IO.MemoryStream oStream = new System.IO.MemoryStream())
{
System.Xml.Serialization.XmlSerializer oSerializer = new System.Xml.Serialization.XmlSerializer(theObject.GetType());
oSerializer.Serialize(oStream, theObject);
return Encoding.Default.GetString(oStream.ToArray());
}
}
对于View在测试中返回的作业,它通过了测试,所以我猜问题来自我的webservice.
请帮助meeee:'(
最佳答案 我认为问题是因为您正在使用Entity Framework,当它获取Job对象时,它正在创建Job类的动态代理.
我之前通过将以下内容添加到DataContext的构造函数中来解决了这个问题
public JobDataContext()
: base("ConnectionString")
{
this.Configuration.ProxyCreationEnabled = false;
}