因为最近的项目中需要运用到在MFC程序中调用WebService里面集成好了的函数,所以特意花了一天的时间来研究WebService的构建以及如何在MFC的程序中添加Web引用,进而来实现在C++ MFC中调用那些WebService中写好的函数,中间也是遇到了一些不懂和不解的地方,好在通过度娘上的一些资料和自己的研究逐一的解决了,写这篇文章的主要目的是,第一:让自己记得更清楚,也方便以后不记得了可以及时回想起来。第二:让其他的一些和我碰到一样问题的朋友能更好的解决此问题。内容仅供参考,如有不对之处希望大家提出来一起交流。
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
namespace MyWebService
{
///
/// Summary description for Service1
///
[WebService(Namespace = "http://192.168.22.36/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "Default Function")]
public string HelloWorld()
{
return "Hello World";
}
// 新添加的方法
[WebMethod(Description = "My Sample Function")]
public int Sum(int a, int b)
{
return a+b;
}
}
}
接下来,你可以debug运行一下你现在的程序,可以看到现在的效果是这样的。
点击"Sum"超链接,跳转到下一个页面。
在编辑框中输入a = 10,b = 100,点击调用,就可以看到XML格式返回的WebService结果。
到这里,就说明我们的Web Service的环境没有问题。接下来,我们要做的就是把我们建立好的Web Service发布到iis服务器上去。
#include "stdafx.h"
#include
#include "WebService.h"
using namespace Service1;
int _tmain(int argc, _TCHAR* argv[])
{
// 初始化com组件运行环境
::CoInitialize(NULL);
// 如果第八行没有命名空间Service1
// 这里可以写成Service1::CService1 ws
CService1 ws;
int nNum1 = 10;
int nNum2 = 100;
int nSum = 0;
HRESULT hr = ws.Sum(nNum1, nNum2, &nSum);
printf("The Sum of the two num is:%d\n",nSum);
getchar();
return 0;
}