我对访问WCF的方式有疑问.我构建了一个安全的WCF服务,从数据库返回数据,它工作正常.现在我需要通过MVC访问这个Web服务(我对它没有足够的了解).
我在Stack Overflow上查了类似的问题,但是我找不到我需要的东西.我按照这个链接但是正如我所说,WCF从SQL返回数据,我用SQL连接我的WCF,当我使用这个例子时,我没有得到预期的结果.
我在MVC中调用的操作,它从SQL返回数据集类型
[OperationContract]
DataSet GetAllbooks(string Title)
Run Code Online (Sandbox Code Playgroud)
在Homecontrller的MVC我写道
ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
public ActionResult Index()
{
DataSet ds = obj.GetAllbooks();
ViewBag.AuthorList = ds.Tables[0];
return View();
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我写道
@{
ViewBag.Title = "AuthorList";
}
<table>
<tr><td>ISBN</td><td>Author</td><td>Price</td></tr>
<%foreach (System.Data.DataRow dr in ViewBag.AuthorList.Rows)
{%>
<tr>
<td><%=dr["ISBN"].ToString()%></td>
<td><%=dr["Author"].ToString() %></td>
<td><%=dr["Price"].ToString() %></td>
</tr>
<% } %>
</table>
Run Code Online (Sandbox Code Playgroud)
我没有得到任何结果
此外,WCF提供的一些服务需要接受来自用户的输入我如何能够做到这一点
谢谢.
这是一个非常基本的问题,但一般来说,你可以添加Web服务引用,并在主Web.Config文件终点的信息,但我怀疑你有与调用WCF服务URL的麻烦,如果是这样我贴一个泛型类的例子/ wrapper用于在MVC应用程序中调用WCF Web服务.
将Web引用添加到Visual Studio 2012:
您可能已经知道上述内容,可能只需要一个通用的包装类,这使得在MVC中轻松调用WCF Web服务.我发现使用泛型类效果很好.我不能相信它; 在互联网上找到它并且没有归属.有一个与在下载的源代码的完整范例http://www.displacedguy.com/tech/powerbuilder-125-wcf-web-services-asp-net-p3调用该使用的PowerBuilder 12.5做出一个WCF Web服务. Net,但无论是在Visual Studio还是PowerBuilder中创建,在MVC中调用WCF Web服务的过程都是相同的.
下面是在ASP.NET MVC中调用WCF Web服务的通用包装类的代码
当然,在我的不完整的例子后,不要模拟你的错误处理...
using System;
using System.ServiceModel;
namespace LinkDBMvc.Controllers
{
public class WebService<T>
{
public static void Use(Action<T> action)
{
ChannelFactory<T> factory = new ChannelFactory<T>("*");
T client = factory.CreateChannel();
bool success = false;
try
{
action(client);
((IClientChannel)client).Close();
factory.Close();
success = true;
}
catch (EndpointNotFoundException e)
{
LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
}
catch (CommunicationException e)
{
LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
}
catch (TimeoutException e)
{
LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
}
catch (Exception e)
{
LinkDBMvc.AppViewPage.apperror.LogError("WebService", e, "Check that the Web Service is running");
}
finally
{
if (!success)
{
// abort the channel
((IClientChannel)client).Abort();
factory.Abort();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)