WCF Configuration Hell?

前端 未结 7 934
一生所求
一生所求 2021-02-08 01:07

I hate WCF setup with endpoints, behaviors etc. I believe all these things should be performed automatically. All I want to do is to return JSON result from my WCF service. Here

相关标签:
7条回答
  • 2021-02-08 01:55

    I personally don't like all of the configuration options that WCF offers (I've ranted about it before), and in your case you don't need to use configuration at all. For a simple service to return JSON, you can use a service host factory, and there's one which does exactly that (set up a webHttpBinding/webHttp behavior endpoint), the System.ServiceModel.Activation.WebServiceHostFactory. In your case, you can:

    • Remove everything from config (really, you don't need config at all)
    • Update your .svc file to reference that factory (see below)

    That's it. Here's what the .svc should look like:

    <%@ ServiceHost Language="C#" Service="HighOnCodingWebApps.ZombieService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
    

    One more thing: I noticed that your class isn't decorated with [ServiceContract], but you have a [WebGet] attribute in your method in the class. If the interface (IZombieService) is the one decorated with [ServiceContract], then the method in the interface should be the one decorated with [WebGet]. You can also bypass the interface completely and decorate the ZombieService class with `[ServiceContract] as well.

    [ServiceContract]
    public class ZombieService
    {
        [WebGet(ResponseFormat = WebMessageFormat.Json,
                UriTemplate = "KnownZombies")]
        public Zombie GetZombie()
        {
           return new Zombie() { Name = "Mohammad Azam"};
        }
    }
    
    public class Zombie
    {
        public string Name { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题