使用ASP.Net的WCF服务



我是WCF新手。

我编写了下面的服务,它运行良好。然后配置IIS,并通过浏览器http://localhost/WCF_Entity_SVC/ProductService.svc运行该服务,它运行得很好。我创建了一个ASP。Net网页,并使用url添加了一个服务引用。当我运行ASP页面时,我收到一个内部错误。如有任何帮助,不胜感激。

public class ProductService : IProductService
    {
        public Product GetProduct(int id)
        {
            NorthwindEntities context = new NorthwindEntities();
            var productEntity = (from p
                                 in context.ProductEntities
                                 where p.ProductID == id
                                 select p).FirstOrDefault();
            if (productEntity != null)
                return TranslateProductEntityToProduct(productEntity);
            else
                throw new Exception("Invalid product id");
        }
        private Product TranslateProductEntityToProduct(
              ProductEntity productEntity)
        {
            Product product = new Product();
            product.ProductID = productEntity.ProductID;
            product.ProductName = productEntity.ProductName;
            product.QuantityPerUnit = productEntity.QuantityPerUnit;
            product.UnitPrice = (decimal)productEntity.UnitPrice;
            product.Discontinued = productEntity.Discontinued;
            return product;
        }
    }

ASP代码
 public partial class _Default : System.Web.UI.Page
    {
        myService.ProductServiceClient objService = new ProductServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
           var results = objService.GetProduct(45);   //debug shows internal error
           dgResult.DataSource = results;
           dgResult.DataBind();
        }
    }

在webconfig中添加debug显示以下错误:

The underlying provider failed on Open. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
        Exception Details: System.ServiceModel.FaultException`1[[System.ServiceModel.ExceptionDetail, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]: The underlying provider failed on Open.
        Source Error: 

        Line 159:        
        Line 160:        public ASPWFC.myService.Product GetProduct(int id) {
        Line 161:            return base.Channel.GetProduct(id);
        Line 162:        }
        Line 163:    }
    Source File: D:My DocumentsVisual Studio 2010ProjectswcfWCF_EntityASPWFCService ReferencesmyServiceReference.cs    Line: 161 
    Stack Trace: 

    [FaultException`1: The underlying provider failed on Open.]
       System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9464367
       System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
       ASPWFC.myService.IProductService.GetProduct(Int32 id) +0
       ASPWFC.myService.ProductServiceClient.GetProduct(Int32 id) in D:My DocumentsVisual Studio 2010ProjectswcfWCF_EntityASPWFCService ReferencesmyServiceReference.cs:161
       ASPWFC._Default.Page_Load(Object sender, EventArgs e) in D:My DocumentsVisual Studio 2010ProjectswcfWCF_EntityASPWFCDefault.aspx.cs:23
       System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +37
       System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +95
       System.Web.UI.Control.OnLoad(EventArgs e) +145
       System.Web.UI.Control.LoadRecursive() +134
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3412

为了调试目的,我向服务添加了一个名为Getparams(int id)的函数该函数所做的只是返回id。我调用了ASp页面中的Getparams函数,并得到了传递的参数。我认为这意味着GetProduct函数中的参数被传递给服务,并且在链接到实体查询的某个地方,是错误的。

我不明白的是为什么当我直接运行服务时,没有错误。数据库给我一个结果

我做了更多的调试,我发现打开错误的原因是:

sqlError: Login failed for IIS AppPoolASP。Net4

如何解决这个问题,我的sqlserver是通过windows认证运行的

我在msdn中找到了一个修复安全问题的脚本,并且代码知道工作

CREATE LOGIN [IIS APPPOOLASP.NET v4.0] 
  FROM WINDOWS WITH DEFAULT_DATABASE=[Northwind], 
  DEFAULT_LANGUAGE=[us_english]
GO
CREATE USER [NWUser] 
  FOR LOGIN [IIS APPPOOLASP.NET v4.0]
GO
EXEC sp_addrolemember 'db_datareader', 'NWUser'
GO

在调试WCF服务时,确实有助于启用跟踪。这可以让你诊断模糊的消息("500内部服务器错误"并没有真正给出太多信息),而不会造成太多混乱。

到这里:http://msdn.microsoft.com/en-us/library/ms732023.aspx查看详细信息。总之,添加

<system.diagnostics>
    <trace autoflush="true" />
    <sources>
            <source name="System.ServiceModel" 
                    switchValue="Information, ActivityTracing"
                    propagateActivity="true">
            <listeners>
               <add name="sdt" 
                   type="System.Diagnostics.XmlWriterTraceListener" 
                   initializeData= "c:tempwcfserver.log" />
            </listeners>
         </source>
    </sources>
</system.diagnostics>

发送给您的客户端、服务器或两者;在initializeData中适当调整日志文件名。

运行程序,应该会看到一两个日志文件。使用Service Trace Viewer (Windows SDK的一部分,安装在更高版本的Windows中)打开它们,您应该会看到红色突出显示的异常。

WCF引发的异常,特别是内部异常,通常非常显式,所以这绝对是值得的。

(这也适用于System.Runtime.Serialization,它最近拯救了我几次培根。)

最新更新