Home > database >  Pass type as parameter to controller and use it for xml deserialize
Pass type as parameter to controller and use it for xml deserialize

Time:09-26

Hello I am currently stucking with the following problem. I want to pass a type as parameter to controller and use it to deserialize a a xml string. What I have tried looks like this

            var typeAsString = typeof(List<ProjectReportDto>).GetType().FullName;
            //... pass value to controller 
            
            // in the method I got the string 
            var type = Type.GetType(typeAsString ); 
            var mySerializer = new XmlSerializer(type);
            // I got a Exceptrion -> System.RuntimeType is inaccessible due to its protection level. Only public types can be processed.

Class ProjectReportDto

[Serializable]
public class ProjectReportDto
{
    public string ShortName { get; set; }

    public string LongName { get; set; }

    public string Description { get; set; }

    public DateTime? StartDate { get; set; }

    public DateTime? EndDate { get; set; }

    public string CustomerName { get; set; }
}

Xml string

<?xml version="1.0" encoding="UTF-16"?>
<ArrayOfProjectReportDto xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ProjectReportDto>
<ShortName>Piper .NET</ShortName>
    <LongName>The new Internet</LongName>
    <Description>awsome</Description>
    <StartDate>2022-08-19T00:00:00</StartDate>
    <EndDate>2023-02-25T00:00:00</EndDate>
</ProjectReportDto>
<ProjectReportDto>
    <ShortName>Nucleus</ShortName>
    <LongName>Nucleus Portal </LongName>
    <Description>Make the world a better place </Description>
    <StartDate>2022-08-19T00:00:00</StartDate>
    <EndDate>2026-09-26T00:00:00</EndDate>
</ProjectReportDto>
</ArrayOfProjectReportDto

I have already searched for the problem but I did not found something that helped me. Maybe it is not possible to read a xml this way ?

CodePudding user response:

You call variable.GetType() to get the type of the variable, but calling GetType() on the type itself will return "System.Runtime" which is inaccessible (not public).

Replace

var typeAsString = typeof(List<ProjectReportDto>).GetType().FullName;

With

var typeAsString = typeof(List<ProjectReportDto>).FullName;
  • Related