简体   繁体   中英

WCF Rest Change name of root return element

I have

[OperationContract]
[WebInvoke(Method = "POST",
    ResponseFormat = WebMessageFormat.Xml,
    RequestFormat = WebMessageFormat.Xml,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "projects/{projectname}")]
[return: MessageParameter(Name = "ProjectId")]
Guid CreateProject(String projectName);

But this still returns

<guid 
xmlns="http://schemas.microsoft.com/2003/10/Serialization/">00000000-0000-0000-0000-00000000</guid>

How do I replace "guid" with ProjectId?

public Guid CreateProject(String projectName)
{
     return Guid.Empty;
}

If I change the OperationContract BodyStyle to WrappedResponse I get:

<CreateProjectResponse 
    xmlns="http://tempuri.org/">
    <ProjectId>00000000-0000-0000-0000-000000000</ProjectId>
</CreateProjectResponse>

Which is almost what I want, but I don't want unnecessarily wrapped.

You become what you have defined. You have defined to receive empty GUID in XML form and it returns to you empty GUID in XML. All is right.

Maybe you need convert GUID to some kind of string id, then Guid.NewGuid().ToString("N")

When you aren't expecting xml then you need to fit attributes and use HTTP Accept Header from client, for example for Json Accept: application/json , or string - plain/text

UPD: Now a little bit clear. Your actually ask how to change XML structure. I recommend you for standard types use standard XML structure because you already have implemented from the box XML formatters. Anyway when you need to change formatters, you can do it by extending the WebHttpBehavior and overriding the WebHttpBehavior.GetReplyDispatchFormatter method to return our own custom implementation of System.ServiceModel.Dispatcher.IDispatchFormatter (as example read here )

I want also just mention, that you are using WCF 4 REST, and this technology is legacy. When you are dealing not with legacy project or maintenance, then I recommend you to use ASP.NET Web API , because this and many other things could be done there much more easier.

Easiest solution is to

return new XElement("ProjectId", Guid.Empty);

Not really what I wanted, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM