2016-09-09 29 views
0

我最近在包含RESTful WCF服務的C#.Net解決方案中實現了Autofac作爲IoC容器。這似乎工作得很好,直到我們的一些消費者發現他們無法通過將Accept標頭設置爲application/xml來獲得XML響應。現在只會返回JSON,而不管Accept頭是什麼。接受:在RESTful WCF服務上實現Autofac後,application/xml不再有效

我認爲這個問題是由於需要實現Autofac的Service.svc文件中的Factory="System.ServiceModel.Activation.WebServiceHostFactory"替換爲Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf"

有沒有人有解決方案?

下面是一個簡化但代表性的代碼示例。

Service.svc:

<%@ ServiceHost 
    Language="C#" 
    Service="MySolution.MyService, MySolution.MyService" 
    CodeBehind="WcfServiceImplementations/Service.cs" 
    Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" 
%> 

IMyService.cs:

... 
[ServiceContract(Name = "MyService", Namespace = "WebServices")] 
[ServiceKnownType(typeof(Object))] 
public interface IMyService 
{ 
    /// Comments 
    [OperationContract] 
    [WebGet(UriTemplate = "Method/{Id}", 
      BodyStyle = WebMessageBodyStyle.Bare, 
      RequestFormat = WebMessageFormat.Json, 
      ResponseFormat = WebMessageFormat.Json)] 
    Object MyMethod(string Id); 
    ... 
} 

MyService.cs:

... 
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
public class MyService : IMyService 
{ 
    private readonly IMyDependency _myDependency; 

    public MyService (IMyDependency myDependency) 
    { 
     _myDependency = myDependency;   
    } 

    public Object MyMethod(string Id) 
    { 
     // Method code here 
    } 
    ... 
} 

Global.asax中:

public class Global : HttpApplication 
{ 
    private void Application_Start(object sender, EventArgs e) 
    { 
     // Autofac initialization is actually in another class, but we call it here like this 
     var builder = new ContainerBuilder(); 

     builder.RegisterType<MyService>().AsSelf(); 

     builder.RegisterType<MyDependency>().As<IMyDependency>();    

     var container = builder.Build(); 

     AutofacHostFactory.Container = container; 
     ... 
    } 
} 
從提琴手

原始請求:

GET http://localhost/MySolution/MyService.svc/MyMethod/12345 HTTP/1.1 
Accept: application/xml 
Authorization: meyer.john 

回答

1

嘗試AutofacWebServiceHostFactory代替AutofacServiceHostFactory。

+0

謝謝!這工作!截至2016年12月9日,在http://docs.autofac.org/en/latest/上沒有提及該工廠。 –