WebAPI调用引入了xml命名空间,导致反序列化失败

时间:2014-10-31 12:06:27

标签: asp.net-web-api

我有一个像这样的WebAPI方法:

[HttpPost, Route("api/student/studentstatus")]
public UpdatedStudent StudentStatus(HttpRequestMessage request)
{
    string requestData = request.Content.ReadAsStringAsync().Result;
    GetStudentStatus scp = null;
    XmlSerializer serializer = new XmlSerializer(typeof(GetStudentStatus), new XmlRootAttribute("GetStudentStatus"));
    using (Stream stream = request.Content.ReadAsStreamAsync().Result)
    {
        scp = (GetStudentStatus)serializer.Deserialize(stream);
    }
}

这是requestData

中的字符串
<GetStudentStatus xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/StudentStatusConsole">
<StudentID></StudentID><Batch></Batch>
</GetStudentStatus>

当StudentStatus被击中时,它会在Deserialize部分死亡并出现此错误:

"<GetStudentStatus xmlns='http://schemas.datacontract.org/2004/07/StudentStatusConsole'> was not expected."}

这是GetStudentStatus类:

public class GetStudentStatus
{
    public string StudentID { get; set; }
    public string Batch { get; set; }
}

尝试使用DataContract(NameSpace =&#34;&#34;)注释该类,并将DataMember属性添加到属性中。 不行。

这是调用WebAPI的方法:

using (var client = new HttpClient())
{
    GetStudentStatus studentToPost = new GetStudentStatus() { StudentID = "", Batch = "" };
    client.BaseAddress = new Uri("http://localhost:53247/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

    HttpResponseMessage response = await client.PostAsXmlAsync("api/student/studentstatus", studentToPost);
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

尝试使用DataContract属性注释GetStudentStatus类,但指定Namespace属性,使其包含类所在的命名空间。

[DataContract(Name = "GetStudentStatus", Namespace = "http://schemas.datacontract.org/2004/07/[NameSpace]")]
public class GetStudentStatus
{
    public string StudentID { get; set; }
    public string Batch { get; set; }
}