一个Web交互中可能用到WCF,没想到其他方案,再重新学习一下,参考一个博文
https://blog.csdn.net/weifaqiang/article/details/77618509
删除自动创建的WCF服务,然后添加新建WCF服务的接口和实现,注意有两个WCF模板可选
接口如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;
namespace WcfService3_test_ajax
{
[ServiceContract]
public interface ITaskInfo
{
[OperationContract]
[WebGet(UriTemplate = "/DoWork?name={name}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string DoWork(string name);
[OperationContract]
[WebGet(UriTemplate = "/Delete", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
System.IO.Stream Delete();
[OperationContract]
[WebGet(UriTemplate = "/Json")]
string Json();
}
}
实现如下
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Serialization;
namespace WcfService3_test_ajax
{
//[ServiceContract(Namespace = "")] 注意一
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TaskInfo: ITaskInfo
{
// 要使用 HTTP GET,请添加 [WebGet] 特性。(默认 ResponseFormat 为 WebMessageFormat.Json)
// 要创建返回 XML 的操作,
// 请添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// 并在操作正文中包括以下行:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
//[OperationContract] 注意二
public string DoWork(string name)
{
return "Hello World!:" + name;
}
// 在此处添加更多操作并使用 [OperationContract] 标记它们
public Stream Delete()
{
return GetStream(@"{""data"":""OK!!!!!!""}");
}
public string Json()
{
string res = null;
Student stu = new Student
{
StuID = 3,
StuName = "郭大侠"
};
Student stu1 = new Student
{
StuID = 31,
StuName = "郭大侠1"
};
UserInfo u = new UserInfo("3", "郭大侠");
UserInfo u1 = new UserInfo("31", "郭大侠1");
List<Student> list = new List<Student>();
List<UserInfo> list1 = new List<UserInfo>();
list.Add(stu);
list.Add(stu1);
list1.Add(u);
list1.Add(u1);
using (MemoryStream ms = new MemoryStream())
{
XmlObjectSerializer sz = null;
sz = new DataContractJsonSerializer(list.GetType());
sz.WriteObject(ms, list);
sz = new DataContractJsonSerializer(list1.GetType());
sz.WriteObject(ms, list1);
res = Encoding.UTF8.GetString(ms.ToArray());
}
return res;
}
private Stream GetStream(string str)
{
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
sw.AutoFlush = true;
sw.Write(str);
ms.Position = 0;
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
return ms;
}
private Stream GetStreamJson(Object obj)
{
string str;
if (obj is String || obj is Char)
{
str = obj.ToString();
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
str = serializer.Serialize(obj);
}
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
sw.AutoFlush = true;
sw.Write(new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json"));
ms.Position = 0;
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
return ms;
}
}
}
二、WCF配置
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<!-- 浏览器可访问的设置项 -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehavior33">
<!--<enableWebScript/>--> 注意三
<!-- 此处设为true,可以使得输出String时去掉json格式的外层引号-->
<webHttp automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<services>
<service name="WcfService3_test_ajax.TaskInfo">
<endpoint address="" behaviorConfiguration="webBehavior33"
binding="webHttpBinding" contract="WcfService3_test_ajax.ITaskInfo" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
三、DataContract
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace WcfService3_test_ajax
{
[DataContract]
public class UserInfo
{
[DataMember]
private string name;
[DataMember]
private string sex;
public UserInfo(string name, string sex)
{
this.name = name;
this.sex = sex;
}
}
}
四、发布
发布方法:文件系统
复制到IIS站点,测试
五、结果,在浏览器中查看也行
参见注意一。
参见注意二。
参见注意三。
完成