Return Different JSON in WCF method on error

I have a method which return a class cono in Json format

  [DataContract]
public class Cono
{
    [DataMember(Order = 1)]
    public Companies[] companies;

}
public class Companies
{
    [DataMember(Order = 1)]
    public string cono;
    [DataMember(Order = 2)]
    public string name;
}

      [WebGet(UriTemplate = "GetCompanies?requestKey={requestKey}",
ResponseFormat = WebMessageFormat.Json)]
        public Cono GetCompanies(string requestKey);

this method first validate request key if it is correct it returns data like this:

{
companies: [
{
cono: "001",
name: "Company001"
}
]
}

but if request key is not correct I want to return an error code in json like this

{-100}

How can I change the return type of the method to Int or how can I return desired data in the above format

Answers


You can change the return type of your method to Stream (public Stream GetCompanies(string requestKey);) and write a method

static Stream ToJson(object o)
{
    var result = JsonConvert.SerializeObject(o);
    var data = Encoding.UTF8.GetBytes(result);

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
    WebOperationContext.Current.OutgoingResponse.ContentLength = data.Length;
    return new MemoryStream(data);
}

Then, in your method, you can use it as

........
return ToJson(anyObject)

What about changing your return type to something like this?

[DataContract]
public class Cono
{
    [DataMember(Order = 1)]
    public Companies[] companies;

    [DataMember(Order = 2)]
    public Error error;    
}

public class Error
{
    public int code;
    public string message;
}

Then if you have an error, companies will be null and the error will be set. If you don't have an error, error will be null and companies will be set.


Need Your Help

Any tools to get code churn metrics for a Subversion repository?

svn project-management

I'm looking for any tools that can give you code churn metrics (graphs and charts would be even better) for a Subversion repository.

How to write a channel.html file in Rails (for Facebook)

ruby-on-rails facebook

According to the FB SDK I must include a channel file with the appropriate headers.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.