【问题标题】:Accept: application/xml no longer working after Autofac implementation on RESTful WCF Services接受:在 RESTful WCF 服务上实现 Autofac 后,application/xml 不再工作
【发布时间】:2016-09-09 21:31:05
【问题描述】:

我最近在包含 RESTful WCF 服务的 C#.Net 解决方案上将 Autofac 实现为 IoC 容器。这似乎工作得相当好,直到我们的一些消费者注意到他们无法通过将 Accept 标头设置为 application/xml 来获得 XML 中的响应。现在,无论 Accept 标头如何,它都只会返回 JSON。

我认为问题源于在实现 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
    }
    ...
}

全球.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;
        ...
   }
}

来自 Fiddler 的原始请求:

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

【问题讨论】:

    标签: c# rest wcf autofac


    【解决方案1】:

    尝试AutofacWebServiceHostFactory 而不是 AutofacServiceHostFactory。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 2014-05-25
    相关资源
    最近更新 更多