域连接字符串和应用程序设置已由域层获取

时间:2013-02-20 17:57:03

标签: c# asp.net asp.net-mvc-4

任何人都可以帮助解决这个问题,我在发布到网络主机之前已将网站发布到本地iis7,现在没有关闭我的数据库连接或应用程序设置,因此我得到了

[NullReferenceException: Object reference not set to an instance of an object.]

我的网站是一个包含2个项目的解决方案1项目是一个包含数据库数据的类库,并且调用远程站点,第二个项目包含我所有的ui数据,控制器帮助程序等。

所以我有Web.Domain和Web.UI。

如果我有以下基本课程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Web.Domain.EAN
 {
public class testFromDomain : ItestFromDomain
    {
   public string testdata()
       {
       return "test from domain";
       }
    }
}

这样可行,所以我认为我的配置文件有问题

有谁知道我做错了什么或错过了什么。

我的网站是MVC4

-------------------- FULL ERROR ------------------

'/'应用程序中的服务器错误。

对象引用未设置为对象的实例。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

来源错误:

在执行当前Web请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常的起源和位置的信息。

堆栈追踪:

  

[NullReferenceException:对象引用未设置为对象的实例。]     Web.UI.Helpers.Weather.GetWeatherCurrentForcast.data(String id)+1947     System.Threading.Tasks.Task`1.InnerInvoke()+78     System.Threading.Tasks.Task.Execute()+ 109     System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)+144   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)+84     Web.UI.Controllers.d__3.MoveNext()+ 462      System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)+144      System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)+84      lambda_method(Closure,Task)+57      System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult)+105      System.Web.Mvc.Async。<> c_ DisplayClass3f.b _3e(IAsyncResult asyncResult)+22      System.Web.Mvc.Async。<> c_ DisplayClass39.b _33()+124      System.Web.Mvc.Async。<> c_ DisplayClass4f.b _49()+838059      System.Web.Mvc.Async。<> c_ DisplayClass37.b _36(IAsyncResult asyncResult)+15      System.Web.Mvc.Async。<> c_ DisplayClass2a.b _20()+33      System.Web.Mvc.Async。<> c_ DisplayClass25.b _22(IAsyncResult asyncResult)+838644      System.Web.Mvc。<> c_ DisplayClass1d.b _18(IAsyncResult asyncResult)+28      System.Web.Mvc.Async。<> c_ DisplayClass4.b _3(IAsyncResult ar)+15      System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)+65      System.Web.Mvc.Async。<> c_ DisplayClass4.b _3(IAsyncResult ar)+15      System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)+51      System.Web.Mvc。<> c_ DisplayClass8.b _3(IAsyncResult asyncResult)+42      System.Web.Mvc.Async。<> c_ DisplayClass4.b _3(IAsyncResult ar)+15      System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)+51      System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar)+282


版本信息:Microsoft .NET Framework版本:4.0.30319; ASP.NET版本:4.0.30319.18034

---------------------访客评论的完整代码------------------

    using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace Web.Domain.VisitorReviews
    {
    public class DisplayVisitorReviews
        {
        public string ForumImageID      { get; private set; }
        public string ForumPostTitle    { get; private set; }
        public string ForumCity         { get; private set; }
        public string ForumRegion       { get; private set; }
        public string ForumCountry      { get; private set; }
        public string ForumPost         { get; private set; }
        public string ForumRatePost     { get; private set; }
        public string ForumMember       { get; private set; }
        public string ForumImageType    { get; private set; }
        public byte[] ForumImage        { get; private set; }

                  public DisplayVisitorReviews(string ForumImageID,
                                               string ForumPostTitle,
                                               string ForumCity,
                                               string ForumRegion,
                                               string ForumCountry,
                                               string ForumPost,
                                               string ForumRatePost,
                                               string ForumMember,
                                               string ForumImageType,
                                               byte[] ForumImage)
            {
            this.ForumImageID       = ForumImageID;
            this.ForumPostTitle     = ForumPostTitle;
            this.ForumCity          = ForumCity;
            this.ForumRegion        = ForumRegion;
            this.ForumCountry       = ForumCountry;
            this.ForumPost          = ForumPost;
            this.ForumRatePost      = ForumRatePost;
            this.ForumMember        = ForumMember;
            this.ForumImageType     = ForumImageType;
            this.ForumImage         = ForumImage;
            }
        }
    public class GetVisitorReviews : IGetVisitorReviews
        {
        private string dbConn;

        public GetVisitorReviews()
            {
            dbConn = ConfigurationManager.ConnectionStrings["Website"].ConnectionString;
            }
        public IEnumerable<DisplayVisitorReviews> DisplayTopTenVisitorReviews(string id)
            {
            //string cacheTopTenDestinationReports        = "TopTenDestinationReports + "-"+ id";
            //string TopTenDestinationReportsCacheKey     = cacheTopTenDestinationReports;
            //MemoryCache CacheTopTenDestinationReports   = MemoryCache.Default;

            //if (CacheTopTenDestinationReports.Contains(TopTenDestinationReportsCacheKey))
            //    return CacheTopTenDestinationReports[TopTenDestinationReportsCacheKey] as IEnumerable<DisplayVisitorReviews>;

            string spName = "dbo.GetTopTenForumPosts";
            using (SqlConnection cn = new SqlConnection(dbConn))
                {
                using (SqlCommand cmd = new SqlCommand(spName, cn))
                    {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("@strLocation", SqlDbType.VarChar, 150));
                    cmd.Parameters["@strLocation"].Value = id;

                    List<DisplayVisitorReviews> lst = new List<DisplayVisitorReviews>();
                    try
                        {
                        cn.Open();
                        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.Default))
                            {
                            if (rdr.HasRows)
                                {
                                while (rdr.Read())
                                    {
                                    DisplayVisitorReviews GetData = new DisplayVisitorReviews(
                                                                                   Convert.ToString((Guid)rdr["ForumImageID"]),
                                                                                   (string)rdr["ForumPostTitle"],
                                                                                   (string)rdr["ForumCity"],
                                                                                   (string)rdr["ForumRegion"],
                                                                                   (string)rdr["ForumCountry"],
                                                                                   (string)rdr["ForumPost"],
                                                                                   Convert.ToString((int)rdr["ForumRatePost"]),
                                                                                   (string)rdr["ForumMember"],
                                                                                   (string)rdr["ForumImageType"],
                                                                                   (byte[])rdr["ForumImage"]);
                                    lst.Add(GetData);
                                    }
                                }
                            }

                        //CacheItemPolicy policy = new CacheItemPolicy();
                        //policy.AbsoluteExpiration = DateTime.Now.AddHours(1);
                        //CacheTopTenDestinationReports.Add(TopTenDestinationReportsCacheKey, lst.AsEnumerable(), policy);

                        return lst;

                        }
                    catch (Exception ex)
                        {
                        throw new ApplicationException(ex.InnerException.ToString());
                        }
                    }
                }
            }
        }
    }



using System;
using System.Collections.Generic;
namespace Web.Domain.VisitorReviews
    {
    public interface IGetVisitorReviews
        {
        IEnumerable<DisplayVisitorReviews> DisplayTopTenVisitorReviews(string id);
        }
    }


kernel.Bind<IGetVisitorReviews>().To<GetVisitorReviews>().InSingletonScope();

 private readonly IGetVisitorReviews _IGVR;

    public MembersController(IGetVisitorReviews IGVR)
        {
        _IGVR = IGVR;
        }

public PartialViewResult pvVisitorReviews()
            {

                var destinations = _IGVR.DisplayTopTenVisitorReviews("NA").Take(5);
                return PartialView("pvHomePageVisitorReviews",destinations);
            }

 <add name="Website" connectionString="Data Source=Windows7\SQL2012;Initial Catalog=WebsiteDB;Persist Security Info=true; Integrated Security=SSPI" providerName="System.Data.SqlClient" />

我已经为评论添加了完整代码,原因是代码量最短。此外,如果我注释掉了天气局部视图,那么同样的错误会转到评论中,如果我注释掉评论或其他任何从网站加载的web.config引用的内容。

------------------------在类-------------

Server Error in '/' Application.
--------------------------------------------------------------------------------


 Object reference not set to an instance of an object. 
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.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 





Line 87:                 <div class="dvAsyncDestination">
Line 88:                    
Line 89:                   @{Html.RenderAction("pvVisitorReviews", "Members", true);}
Line 90:                    
Line 91:                 </div> 

Source File: f:\LocalTestSite\Views\Home\Index.cshtml    Line: 89 

Stack Trace: 





[NullReferenceException: Object reference not set to an instance of an object.]
   Web.UI.Controllers.MembersController.pvVisitorReviews() +184
   lambda_method(Closure , ControllerBase , Object[] ) +78
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +260
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +38
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +33
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +123
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +838059
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +838644
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
   System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +15
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +41
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1783

[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +2819
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +275
   System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +94
   System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +700
   DevTrends.MvcDonutCaching.HtmlHelperExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, Boolean excludeFromParentCache) +233
   DevTrends.MvcDonutCaching.HtmlHelperExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, Boolean excludeFromParentCache) +17
   ASP._Page_Views_Home_Index_cshtml.Execute() in f:\LocalTestSite\Views\Home\Index.cshtml:89
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +280
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +126
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +143
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +181
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +378
   System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +33
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +854172
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +838644
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288



--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034 

2 个答案:

答案 0 :(得分:1)

我已经解决了这个问题而且只用了1天:-(对于遇到此问题的其他人请查看此链接Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

上面发布的链接让我走上正轨,但微软建议使用ApplicationPoolIdentity,这就是我为解决问题所做的工作。

  1. 打开SQL,然后打开安全性
  2. 单击登录并右键单击并选择新登录
  3. 为其命名为IIS APPPOOL \ ASP.NET v4.0
  4. 然后默认数据库选择您想要的数据库
  5. 单击服务器角色并选择公共
  6. 点击用户映射并选择所有者和公共,(我必须选择两者才能使其生效)
  7. 点击确定然后退出安全
  8. 现在点击您的数据库并选择安全性
  9. 单击用户并选择IIS APPPOOL \ ASP.NET v4.0
  10. 右键单击选择属性
  11. Clck拥有架构,然后选择datareader和datawriter
  12. 点击会员资格并选择所有者
  13. 单击“确定”,然后返回到IIS管理器,单击浏览网站,您的站点现在应该可以在IIS中运行。

    3分我不高兴。

    1. 在用户映射中选择所有者,这是否真的需要选择,如果不能如何更好地保护连接
    2. 再次在membsership中选择所有者,为什么我需要选择此项才能使其正常工作。
    3. 最后我读过的所有书籍,没有说明必须将IIS APPPOOL \ ASP.NET v4.0添加到数据库安全性。如果这是让这个工作的唯一方法,请作者,请将这些信息添加到您的书中,这样可以节省我一天的工作量。
    4. 我不是一名专业的程序员,我只是通过追踪和错误以及阅读书籍来学习。因此,如果其他人可以添加上述内容,请执行此操作。

      由于

      乔治

答案 1 :(得分:0)

当您发布网站时,它只发布您的网站项目的Web.config,而不是您的类库项目。您必须手动将连接字符串添加到您网站的Web.config中。