WCF WebService 在应用程序中的应用: 初学者指南






4.56/5 (4投票s)
本文描述了在专业应用程序中编写 WCF 服务的途径
引言
**在阅读本文之前,请先了解什么是 WCF 或为什么需要它(对于初学者)。**
WCF 是一个用于开发面向服务的应用程序的框架,可以将异步消息从一个终结点发送到另一个终结点。 在本文中,我将从专业的应用程序开发角度展示 WCF 应用程序的详细开发过程。
背景
互联网上有许多可用的文章来学习 WCF。 因此,在这里我将扩展我的文章,以从专业的应用程序开发的角度详细展示。 这样,用户就可以在实际应用程序中启动他们的 WCF 服务时轻松使用此代码/文章
第一部分:WCF 服务创建、调试和测试
首先,我们从 Visual Studio 创建一个 WCF 项目
从 Visual Studio->创建新项目->WCF->WCF 服务应用程序
图:1
你创建了什么?
你创建了一个名为 Service1.svc 的服务,请在你的项目中查看。
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
现在的问题是,如何访问服务?
契约
在 WCF 中,所有服务都公开了契约,描述了服务对外部世界的作用。 不同类型的契约:
- 操作契约...
- 数据契约...
- 消息契约...
- 故障契约。
命名空间和名称
默认情况下,公开的契约名称将是所用接口的名称。
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = UriTemplate.LoanCategoryById)]
QueryResult> GetData(int value , string st);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
现在运行它,你将看到类似的输出。
图:2
现在,我将解释如何调用你的服务方法以及如何调试。 之后,你将如何测试你的服务是否工作正常?
1. 运行后,你将在浏览器中看到如图 2 所示的内容。
点击 Service1.svc,你将注意到一个标题为“Service1 Service”的页面
2. 现在,要在你的服务上查看服务方法,请在你的 URL 上使用 /help
使用此链接:https://:16980/Service1.svc/help
你看到什么了吗? 如果没有
请按如下方式更改你的 web config System.service 节点
第二部分:在专业应用程序中工作
你已经完成了服务的基本结构。 继续第一部分。 在你的项目中,你需要遵循一些标准来开发你的应用程序,以实现可扩展性、持久性和可读性。
1. URL 格式
2. 错误处理,并在你的服务中抛出异常
3. 用户和会话检查
4. 分页
5. 信息消息
6. 任何警告消息
7. 操作状态消息
首先,你需要遵循一个标准的 URL 名称,以便用户应用程序调用。
这里我有两个方法 GetData 和 GetDataUsingDataContract。 因此,我需要分配一个有意义的名称,而无需修改我现有的方法名称。
所以我创建了一个类来全局编写 URL 名称
public static class UriTemplate
{
public const string LoanCategoryById = "LoanCategoryById";
public const string LoadAllCategory = "LoadAllCategory";
}
并在 Iservice1 中进行如下更改
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = UriTemplate.LoanCategoryById)]
其次,你需要为每个响应结果返回一个标准的 message 格式。
基本结果类
public class BaseResult
{
private bool operationSuccessful = false;
public bool IsOperationSuccessful
{
get { return this.operationSuccessful; }
set { this.operationSuccessful = value; }
}
private bool isresult = false;
public bool IsResult
{
get { return this.isresult; }
set { this.isresult = value; }
}
private List statusMessages;
public List StatusMessages
{
get { return statusMessages; }
set { statusMessages = value; }
}
private List errorMessages;
public List ErrorMessages
{
get { return errorMessages; }
set { errorMessages = value; }
}
private List infoMessages;
public List InfoMessages
{
get { return infoMessages; }
set { infoMessages = value; }
}
private List warnMessages;
public List WarnMessages
{
get { return warnMessages; }
set { warnMessages = value; }
}
}
public class Message
{
public string Code { get; set; }
public string Text { get; set; }
}
以及下面的查询结果类
public class QueryResult : BaseResult
{
private T result;
public T Result
{
get { return result; }
set { result = value; }
}
public int Total { get; set; }
}
因此,使用此查询结果类,你将处理结果,响应列表中包含多少结果、错误消息、操作状态等。
现在,我已经在 GetData 方法中实现了它
public QueryResult> GetData(int value,string st)
{
QueryResult> result = new QueryResult>();
List responseList = new List();
try
{
if (String.IsNullOrEmpty(st))
{
var err = new List();
err.Add(new Message { Code = "1", Text = "Session Token is missing" });
result.ErrorMessages = err;
return result;
}
else
{
List categories = new List() { new CategoryResponse(){Code="001",Name="Test 1"}, new CategoryResponse(){Code="002", Name="Test 2"}};
//if need any conditional changes
foreach (var item in categories)
{
responseList.Add(item);
}
result.Total = categories.Count;
}
result.Result = responseList;
result.IsOperationSuccessful = true;
return result;
}
catch (Exception ex)
{
result.IsOperationSuccessful = false;
result.IsResult = false;
var err = new List();
err.Add(new Message { Code = "5", Text = ex.Message });
result.ErrorMessages = err;
return result;
}
}
另请更改 IService 方法返回类型,如下所示
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = UriTemplate.LoanCategoryById)]
QueryResult> GetData(int value , string st);
你已经完成了服务。 现在如何测试它。 如何查看结果。
我个人使用 POSTMAN,一个 google chrome 浏览器的插件
https://www.getpostman.com/
从这个链接安装它。
打开它
将你的 URL 粘贴到 URL 上
编写 Body [你用参数传递的]
数据类型 JSON 并运行,你将看到你的结果。
{ "ErrorMessages": null, "InfoMessages": null, "IsOperationSuccessful": true, "IsResult": true, "StatusMessages": null, "WarnMessages": null, "Result": [ { "Code": "001", "Name": "Test 1", "ParentGroupId": 0 }, { "Code": "002", "Name": "Test 2", "ParentGroupId": 0 } ], "Total": 2 }
关注点
本文面向在开发基于服务的应用程序时遇到问题的初学者。 我认为它能更好地帮助他们。
历史
在此处保持您所做的任何更改或改进的实时更新。