WCF JSON和AspnetCompatibility的配置
在WCF Service Application中加入<enableWebScript>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="ajaxbehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="JsonWCF.StudentService">
<endpoint binding="webHttpBinding" contract="JsonWCF.IStudentService" behaviorConfiguration="ajaxbehavior" />
</service>
</services>
</system.serviceModel>
定义Contract,添加[WebGet] Attribute允许HTTP Get访问
[ServiceContract]
public interface IStudentService
{
[OperationContract]
[WebGet]
Student RandomStudent();
}
[DataContract]
public class Student
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public DateTime DOB { get; set; }
}
WCF可以以ASP.NET的方式host,这样就可以使用httpmodule httpcontext等一些asp.net特有的流程
在配置文件中添加
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
...
定义Module (Namespace = JsonWCF)
public class MyModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Application["key"] = "nothing is impossible";
}
}
web.config添加module
<system.web>
<httpModules>
<add name="mymodule" type="JsonWCF.MyModule"/>
...
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class StudentService : IStudentService
{
public Student RandomStudent()
{
string firstname = "null";
if (HttpContext.Current != null)
firstname = HttpContext.Current.Application["key"] as string;
return new Student { DOB = DateTime.Parse("1983/10/14"), FirstName = firstname, LastName = "Zhu" };
}
}
Remarks
如果将配置中的aspnetcompatibilityenabled改为false,wcf将不再走aspnet管道,application始终为空