Security Exception using MySQL and Entity Framewor

2020-02-06 18:16发布

We are getting a SecurityException when using Entity framework on godaddy. The entity has been configured against a MySQL store. (v. 6.1.2) A bit of weirdness with the exception though... Looking at the exception stack it seems to imply that if we open up a connection to MySQL anywhere in the site, then we should get the same exception; however, opening up a MySQL connection directly seems to be working in another part of the site...

Here's the verification:

using (MySqlConnection connection = new MySqlConnection(ConnectionString))
{
  connection.Open();
  ...
}

Anyone run across a similar issue?

The complete error stack trace is as follows:

[SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags) +0
   System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +470
   System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +1051
   System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +111
   System.Resources.ResourceManager.CreateResourceSet(Stream store, Assembly assembly) +357
   System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents) +471
   System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents) +583
   System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents) +583
   System.Resources.ResourceManager.GetString(String name, CultureInfo culture) +74
   MySql.Data.MySqlClient.Resources.get_PerfMonCategoryName() +40
   MySql.Data.MySqlClient.PerformanceMonitor..ctor(MySqlConnection connection) +43
   MySql.Data.MySqlClient.MySqlConnection.Open() +434
   System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +173
   System.Data.EntityClient.EntityConnection.Open() +96
   System.Data.Objects.ObjectContext.EnsureConnection() +81
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +46
   System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44
   jet.Controllers.WorkOrder.WorkOrderView..ctor() +219
   jet.Controllers.WorkOrder.WorkOrderView.get_Instance() +29
   jet.Controllers.WorkItemController.Index() +11
   lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
   System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +53
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
   System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +382
   System.Web.Mvc.Controller.ExecuteCore() +123
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +144
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
   System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

3条回答
贪生不怕死
2楼-- · 2020-02-06 18:29

Weird one. GoDaddy shared-hosting ASP.NET apps execute under Medium Trust, and perf counter creation probably requires full trust, but perf counter creation is not what's failing here. (and if it failed, it wouldn't propagate out since perf coutner creation exceptions are swallowed by mySQL client code).

Instead, it's failing trying to access a string resource, before perf counter creation. The failure is with this line of code in Resources.Designer.cs of the MySQL client:

return ResourceManager.GetString("PerfMonCategoryName", resourceCulture)

A few things to try, in increasing order of difficulty:

  1. ensure you have the MySQL client DLLs in your app's BIN directory and you're not trying to load the client DLL out of GoDaddy's GAC. Never depend on GoDaddy-supplied binaries if you can avoid it!

  2. switch to EN-US culture so the client doesn't have to go hunting for another resource DLL, and see if the problem goes away.

  3. Build the .NET client from source code, instead of copying DLLs from a binary distribution into your app's BIN directory. This will make problems like this easier to debug since the mySQL code won't be a black box. And, in a pinch, will let you change the problematic resource-fetching calls (or hard-code the locale)! :-)

BTW, in case you're tempted to set "Use Performance Monitor=false" in your connection string to try to evade the problem, don't bother. The problematic code gets executed regardless of that setting:

    public PerformanceMonitor(MySqlConnection connection)
    {
        this.connection = connection;

        //// this line is where it bombs
        string categoryName = Resources.PerfMonCategoryName;

        //// this line is affected by connection string setting
        if (connection.Settings.UsePerformanceMonitor && procedureHardQueries == null)
        {
            try
            {
                procedureHardQueries = new PerformanceCounter(categoryName,
                                                              "HardProcedureQueries", false);
                procedureSoftQueries = new PerformanceCounter(categoryName,
                                                              "SoftProcedureQueries", false);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }
    }
查看更多
干净又极端
3楼-- · 2020-02-06 18:29

Justin was spot on. Problem was godaddy has an older version of the MySql dll in their gac and the entity framework was picking it up!

Here's the fix. (Apply this to web.config)

<configuration>
  ...
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d"/>
        <bindingRedirect oldVersion="5.0.7.0" newVersion="6.1.2.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  ...
</configuration>
查看更多
贪生不怕死
4楼-- · 2020-02-06 18:30

I simply added trust level="Full" to my Web config file, and it worked

查看更多
登录 后发表回答