簡體   English   中英

無法序列化對象,因為它沒有無參數的構造函數

[英]Object cannot be serialized because it does not have a parameterless constructor

我正在嘗試編寫一個使用EWS API(2.2)查詢Exchange的Web服務。 我可以使用Console.Write獲取數據,但我想將數據提供給SOAP Web服務的用戶。

我正在使用以下代碼:

public class GetAppointments
{
    public static List<Appointment> GetAppointment()
    {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
        service.UseDefaultCredentials = true;
        //service.Credentials = new WebCredentials("username", "password", "domain");
        service.TraceEnabled = true;
        service.TraceFlags = TraceFlags.All;
        service.AutodiscoverUrl("service@organisation.com", RedirectionUrlValidationCallback);
        //service.ImpersonatedUserId = new ImpersonatedUserID(ConnectingIdType.SmtpAddres, "user@domain");

        // Initialize values for the start and end times, and the number of appointments to retrieve.

        DateTime startDate = DateTime.Now;
        DateTime endDate = startDate.AddDays(30);
        //const int NUM_APPTS = 5;

        // Initialize the calendar folder object with only the folder ID. 
        CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());

        // Set the start and end time and number of appointments to retrieve.

        // CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);

        ItemView view = new ItemView(100);
        // Set the mailbox to query
        String MailBoxToAccess = "myname@organisation.com";
        FolderId CalendarFolderId = new FolderId(WellKnownFolderName.Calendar, MailBoxToAccess);

        // Limit the properties returned to the appointment's subject, start time, and end time.
        view.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);

        // Retrieve a collection of appointments by using the calendar view.

        //FindItemsResults<Appointment> appointments = service.FindAppointments(CalendarFolderId, cView);

        SearchFilter subjectFilter = new SearchFilter.IsEqualTo(AppointmentSchema.Subject, "TEST");

        FindItemsResults<Item> appointments = service.FindItems(CalendarFolderId, subjectFilter, view);

        List<Appointment> AppointmentResult = new List<Appointment>();
        if (appointments.Items.Count > 0)
        {
            foreach (Appointment a in appointments)
            {
                var ApptResult = new Appointment(service)
                    {
                        Subject = a.Subject,
                        Start = a.Start,
                        End = a.End,
                    };

                AppointmentResult.Add(ApptResult);
            }
        }
        else
        {
            return null;
        }

        return AppointmentResult;
    }

    private static bool RedirectionUrlValidationCallback(string redirectionUrl)
    {
        // The default for the validation callback is to reject the URL.
        bool result = false;

        Uri redirectionUri = new Uri(redirectionUrl);

        // Validate the contents of the redirection URL. In this simple validation
        // callback, the redirection URL is considered valid if it is using HTTPS
        // to encrypt the authentication credentials. 
        if (redirectionUri.Scheme == "https")
        {
            result = true;
        }
        return result;
    }
}

當我嘗試運行它時,出現以下錯誤:

* Microsoft.Exchange.WebServices.Data.Appointment無法序列化,因為它沒有無參數的構造函數。

說明:執行當前Web請求期間發生未處理的異常。 請查看堆棧跟蹤,以獲取有關錯誤及其在代碼中起源的更多信息。

異常詳細信息:System.InvalidOperationException:Microsoft.Exchange.WebServices.Data.Appointment無法序列化,因為它沒有無參數構造函數。

源錯誤:當前Web請求的執行期間生成了未處理的異常。 可以使用下面的異常堆棧跟蹤來標識有關異常的來源和位置的信息。

Stack Trace: 
[InvalidOperationException: Microsoft.Exchange.WebServices.Data.Appointment cannot be serialized because it does not have a parameterless constructor.]
   System.Xml.Serialization.TypeDesc.CheckSupported() +5651485
   System.Xml.Serialization.TypeDesc.CheckSupported() +45
   System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError) +172
   System.Xml.Serialization.XmlReflectionImporter.ImportMemberMapping(XmlReflectionMember xmlReflectionMember, String ns, XmlReflectionMember[] xmlReflectionMembers, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +73
   System.Xml.Serialization.XmlReflectionImporter.ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, String ns, Boolean hasWrapperElement, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +286
[InvalidOperationException: There was an error reflecting 'GetAppointmentResult'.]
   System.Xml.Serialization.XmlReflectionImporter.ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, String ns, Boolean hasWrapperElement, Boolean rpc, Boolean openModel, RecursionLimiter limiter) +899
   System.Xml.Serialization.XmlReflectionImporter.ImportMembersMapping(String elementName, String ns, XmlReflectionMember[] members, Boolean hasWrapperElement, Boolean rpc, Boolean openModel, XmlMappingAccess access) +133
   System.Web.Services.Protocols.SoapReflector.ImportMembersMapping(XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, Boolean serviceDefaultIsEncoded, Boolean rpc, SoapBindingUse use, SoapParameterStyle paramStyle, String elementName, String elementNamespace, Boolean nsIsDefault, XmlReflectionMember[] members, Boolean validate, Boolean openModel, String key, Boolean writeAccess) +233
   System.Web.Services.Protocols.SoapReflector.ReflectMethod(LogicalMethodInfo methodInfo, Boolean client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, String defaultNs) +2862
[InvalidOperationException: Method WebService.GetAppointment can not be reflected.]
   System.Web.Services.Protocols.SoapReflector.ReflectMethod(LogicalMethodInfo methodInfo, Boolean client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, String defaultNs) +6262
   System.Web.Services.Description.SoapProtocolReflector.ReflectMethod() +137
   System.Web.Services.Description.ProtocolReflector.ReflectBinding(ReflectedBinding reflectedBinding) +1577
   System.Web.Services.Description.ProtocolReflector.Reflect() +641
   System.Web.Services.Description.ServiceDescriptionReflector.ReflectInternal(ProtocolReflector[] reflectors) +559
   System.Web.Services.Description.ServiceDescriptionReflector.Reflect(Type type, String url) +109
   System.Web.Services.Protocols.DocumentationServerType..ctor(Type type, String uri, Boolean excludeSchemeHostPortFromCachingKey) +230
   System.Web.Services.Protocols.DocumentationServerProtocol.Initialize() +472
   System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) +122
[InvalidOperationException: Unable to handle request.]
   System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) +325
   System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +171
[InvalidOperationException: Failed to handle request.]
   System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +346
   System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +209
   System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47
   System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +226
   System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +145
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155*

我不確定要克服這個問題需要做什么,或者不確定是否要正確解決這個問題。 我願意提出建議。

通過API發送第三方對象並不總是一個好主意,在這種情況下,它肯定是這樣。 您需要考慮到API的使用者需要在另一端重建該類,如果它沒有無參數的構造函數,那是不可能的。

相反,最好創建自己的模型並從中發送所需的值。 例如,假設Appointment類看起來像這樣(我知道不是,但是它只是作為示例):

public class Appointment
{
    public string Title { get; set; }
    public string Body { get; set; }
    public DateTime MeetingTime { get; set; }
}

然后創建自己的模仿“ Appointment的類:

public class AppointmentModel
{
    public string Title { get; set; }
    public string Body { get; set; }
    public DateTime MeetingTime { get; set; }
}

現在,不用返回Appointment ,而是返回自己的模型:

public static List<Appointment> GetAppointment()
{
    //snip
    List<Appointment> appointments = GetAllAppointments()

    //Use some Linq to project into your own model
    return appointments
        .Select(a => new AppointmentModel
        {
            Title = a.Title,
            Body = a.Body,
            MeetingTime = a.MeetingTime
        })
        .ToList();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM