Note that there are some explanatory texts on larger screens.

plurals
  1. POWCF REST Service: WebInvoke with JSON and polymorphism does not work correctly
    primarykey
    data
    text
    <p>I have a typical WCF REST service in C# which accepts JSON input and returns a JSON output:</p> <pre><code>[ServiceContract] public class WCFService { [WebInvoke(Method = "POST", UriTemplate = "register", ResponseFormat = WebMessageFormat.Json)] public BasicResponse RegisterNewUser(UserDTO newUser) { return new BasicResponse() { status = "ERR_USER_NAME" }; } } public class BasicResponse { public string status { get; set; } } public class UserDTO { public string username { get; set; } public string authCode { get; set; } } </code></pre> <p>This works as expected but I want to return different objects in case of normal execution and in case of error. I created a base response class and few inheritors. Now the WCF JSON serializer crashes and produces "400 Bad Request":</p> <pre><code>[ServiceContract] public class WCFService { [WebInvoke(Method = "POST", UriTemplate = "register", ResponseFormat = WebMessageFormat.Json)] public BasicResponse RegisterNewUser(UserDTO newUser) { return new ErrorResponse() { status = "ERR_USER_NAME", errorMsg = "Invalid user name." }; } } public class BasicResponse { public string status { get; set; } } public class ErrorResponse : BasicResponse { public string errorMsg { get; set; } } public class UserDTO { public string username { get; set; } public string authCode { get; set; } } </code></pre> <p>I tried to apply the <code>[KnownType(typeof(ErrorResponse))]</code> and <code>[ServiceKnownType(typeof(ErrorResponse))]</code> attributes without any success. Seems like a bug in the <code>DataContractJsonSerializer</code> which states it supports polymorphism.</p> <p>My WCF REST service uses the WebServiceHostFactory:</p> <pre><code>&lt;%@ ServiceHost Language="C#" Debug="true" Service="WCFService" CodeBehind="CryptoCharService.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %&gt; </code></pre> <p>In my Web.config I have standard HTTP endpoint:</p> <pre><code>&lt;system.serviceModel&gt; &lt;standardEndpoints&gt; &lt;webHttpEndpoint&gt; &lt;standardEndpoint helpEnabled="true" defaultOutgoingResponseFormat="Json" /&gt; &lt;/webHttpEndpoint&gt; &lt;/standardEndpoints&gt; &lt;/system.serviceModel&gt; </code></pre> <p>Do you think this is fixable? I know a workaround (to return string and serialize the output manually) but why this does not work?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload