Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

c# - Model always null on XML POST

I'm currently working on an integration between systems and I've decided to use WebApi for it, but I'm running into an issue...

Let's say I have a model:

public class TestModel
{
    public string Output { get; set; }
}

and the POST method is:

public string Post(TestModel model)
{
    return model.Output;
}

I create a request from Fiddler with the header:

User-Agent: Fiddler
Content-Type: "application/xml"
Accept: "application/xml"
Host: localhost:8616
Content-Length: 57

and body:

<TestModel><Output>Sito</Output></TestModel>

The model parameter in the method Post is always null and I have no idea why. Does anyone have a clue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Two things:

  1. You don't need quotes "" around the content type and accept header values in Fiddler:

    User-Agent: Fiddler
    Content-Type: application/xml
    Accept: application/xml
    
  2. Web API uses the DataContractSerializer by default for xml serialization. So you need to include your type's namespace in your xml:

    <TestModel 
    xmlns="http://schemas.datacontract.org/2004/07/YourMvcApp.YourNameSpace"> 
        <Output>Sito</Output>
    </TestModel> 
    

    Or you can configure Web API to use XmlSerializer in your WebApiConfig.Register:

    config.Formatters.XmlFormatter.UseXmlSerializer = true;
    

    Then you don't need the namespace in your XML data:

     <TestModel><Output>Sito</Output></TestModel>
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...