.NET MVC 4 Membership.CreateUser() Security Exception Forms Authentication - asp.net

I am getting the following error at this line of code...
MembershipUser newuser = Membership.CreateUser(usersvm.username, usersvm.password,
usersvm.email, null, null, true, null, out createStatus);
The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
[SecurityException: The source was not found, but some or all event logs could not be searched. To create the source, you need permission to read all event logs to make sure that the new source name is unique. Inaccessible logs: Security.]
I also have this in the web.config file
<system.web>
<trust level="Full"/>
Here is some stack trace
MySql.Web.Security.MySQLMembershipProvider.WriteToEventLog(Exception e, String action) +380
System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) +207
System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, MembershipCreateStatus& status) +26

I needed to add this writeExceptionsToEventLog = "false" in web.config like this
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider"/>
<add autogenerateschema="true" writeExceptionsToEventLog="false" ....

Related

System.Data.SQLite.SQLiteException: unable to open database file (An exception occurred while initializing the database)

I am trying to use SQLiteCodeFirst with Entity Framework 6.2 and VS2017 15.9.4 to create a simple database.
However the database does not create.
Here is the DbContext
public class HelloDbContext : DbContext
{
public HelloDbContext()
: base("name=ConnectionString")
{
}
public DbSet<Setting> Settings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<HelloDbContext>(modelBuilder);
Database.SetInitializer(sqliteConnectionInitializer);
}
}
Here is the data entity class
public class Setting
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Here is the code that the exception occurs in
using (var ctx = new HelloDbContext())
{
try
{
var obj = new Setting { Name = "blue" };
ctx.Settings.Add(obj);
ctx.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}
Here is app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)"
invariant="System.Data.SQLite.EF6"
description=".NET Framework Data Provider for SQLite (Entity Framework 6)"
type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
<remove invariant="System.Data.SQLite" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite"
description=".Net Framework Data Provider for SQLite"
type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
<entityFramework>
<providers>
<provider invariantName="System.Data.SQLite.EF6"
type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite"
type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=c:\mydb.sqlite" providerName="System.Data.SQLite"/>
</connectionStrings>
</configuration>
Here is the exception
{System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. ---> System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SQLite.SQLiteException: unable to open database file
at System.Data.SQLite.SQLite3.Open(String strFilename, String vfsName, SQLiteConnectionFlags connectionFlags, SQLiteOpenFlagsEnum openFlags, Int32 maxPoolSize, Boolean usePool)
at System.Data.SQLite.SQLiteConnection.Open()
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.DbContextTransaction.EnsureOpenConnection()
at System.Data.Entity.DbContextTransaction..ctor(EntityConnection connection)
at System.Data.Entity.Database.BeginTransaction()
at SQLite.CodeFirst.SqliteInitializerBase`1.InitializeDatabase(TContext context)
at SQLite.CodeFirst.SqliteCreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at HelloSQLite.Form1.button1_Click(Object sender, EventArgs e) in d:\dev\helloSQLite\HelloSQLite\Form1.cs:line 29}
[System.Data.DataException]: {System.Data.DataException: An exception occurred while initializing the database. See the InnerException for details. ---> System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SQLite.SQLiteException: unable to open database file
at System.Data.SQLite.SQLite3.Open(String strFilename, String vfsName, SQLiteConnectionFlags connectionFlags, SQLiteOpenFlagsEnum openFlags, Int32 maxPoolSize, Boolean usePool)
at System.Data.SQLite.SQLiteConnection.Open()
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.DbContextTransaction.EnsureOpenConnection()
at System.Data.Entity.DbContextTransaction..ctor(EntityConnection connection)
at System.Data.Entity.Database.BeginTransaction()
at SQLite.CodeFirst.SqliteInitializerBase`1.InitializeDatabase(TContext context)
at SQLite.CodeFirst.SqliteCreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at HelloSQLite.Form1.button1_Click(Object sender, EventArgs e) in d:\dev\helloSQLite\HelloSQLite\Form1.cs:line 29}
_className: "System.Data.DataException"
_data: null
_dynamicMethods: null
_exceptionMethod: null
_exceptionMethodString: null
_helpURL: null
_HResult: -2146233087
_innerException: {System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SQLite.SQLiteException: unable to open database file
at System.Data.SQLite.SQLite3.Open(String strFilename, String vfsName, SQLiteConnectionFlags connectionFlags, SQLiteOpenFlagsEnum openFlags, Int32 maxPoolSize, Boolean usePool)
at System.Data.SQLite.SQLiteConnection.Open()
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.DbContextTransaction.EnsureOpenConnection()
at System.Data.Entity.DbContextTransaction..ctor(EntityConnection connection)
at System.Data.Entity.Database.BeginTransaction()
at SQLite.CodeFirst.SqliteInitializerBase`1.InitializeDatabase(TContext context)
at SQLite.CodeFirst.SqliteCreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)}
_ipForWatsonBuckets: 18474291
_message: "An exception occurred while initializing the database. See the InnerException for details."
_remoteStackIndex: 0
_remoteStackTraceString: null
_safeSerializationManager: {System.Runtime.Serialization.SafeSerializationManager}
_source: null
_stackTrace: {sbyte[384]}
_stackTraceString: null
_watsonBuckets: null
_xcode: -532462766
_xptrs: 0
Data: {System.Collections.ListDictionaryInternal}
HelpLink: null
HResult: -2146233087
InnerException: {System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.Data.SQLite.SQLiteException: unable to open database file
at System.Data.SQLite.SQLite3.Open(String strFilename, String vfsName, SQLiteConnectionFlags connectionFlags, SQLiteOpenFlagsEnum openFlags, Int32 maxPoolSize, Boolean usePool)
at System.Data.SQLite.SQLiteConnection.Open()
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<Open>b__36(DbConnection t, DbConnectionInterceptionContext c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.EntityClient.EntityConnection.<Open>b__2()
at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.DbContextTransaction.EnsureOpenConnection()
at System.Data.Entity.DbContextTransaction..ctor(EntityConnection connection)
at System.Data.Entity.Database.BeginTransaction()
at SQLite.CodeFirst.SqliteInitializerBase`1.InitializeDatabase(TContext context)
at SQLite.CodeFirst.SqliteCreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)}
IPForWatsonBuckets: 18474291
IsTransient: false
Message: "An exception occurred while initializing the database. See the InnerException for details."
RemoteStackTrace: null
Source: "EntityFramework"
StackTrace: " at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)\r\n at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()\r\n at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)\r\n at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()\r\n at System.Data.Entity.Internal.InternalContext.Initialize()\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)\r\n at System.Data.En
tity.Internal.Linq.InternalSet`1.Add(Object entity)\r\n at System.Data.Entity.DbSet`1.Add(TEntity entity)\r\n at HelloSQLite.Form1.button1_Click(Object sender, EventArgs e) in d:\\dev\\helloSQLite\\HelloSQLite\\Form1.cs:line 29"
TargetSite: {Void PerformInitializationAction(System.Action)}
WatsonBuckets: null
Here are the references
This looks like a permission issue
System.Data.SQLite.SQLiteException: unable to open database file
The database-file is set to c:\mydb.sqlite in app.config connectionString
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=c:\mydb.sqlite" providerName="System.Data.SQLite"/>
</connectionStrings>
Windows is kinda weird at times with files in the system-disk root (try creating a text-file in on system-disk root c:\ with the rightclick-menu-thingy).
You could change the filepath for the connectionString in app.config to a newly created folder, say c:\testing-stuffs\mydb.sqlite (im wildy guessing there is nothing created at c:\mydb.sqlite so there should be no file to move).

Web.Forms project with Owin Startup works with IIS Express but not IIS when not debugging

Some background: I've recently added a Startup.cs file to an older .NET 4.5.1 Web.Forms site in order to allow SSO authentication. I have another new project in the same solution which hosts the SSO code (IdentityServer3). I'd like to run both on local IIS (IIS 10) instead of IIS express so I can switch back and forth debugging the code.
Here's the code that calls out to the SSO process. It's in page_load for testing purposes.
protected void Page_Load(object sender, EventArgs e)
{
var authProps = new AuthenticationProperties { };
HttpContext.Current.GetOwinContext().Authentication.Challenge(authProps);
}
And the startup code for the client:
[assembly:OwinStartup(typeof(MyNamespace.Startup))]
namespace MyNamespace
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var authority = SSOSettings.SSOBaseUrl;
var myUrl = "http://localhost/MyNamespace_WebApp/";
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",
SignInAsAuthenticationType = "Cookies",
Authority = authority,
ClientId = "myclientid",
RedirectUri = myUrl,
PostLogoutRedirectUri = myUrl + "open/Login.aspx",
ResponseType = "id_token token",
Scope = "openid profile email",
UseTokenLifetime = false
});
}
}
When the web project (the SSO client) is being debugged, either using IIS Express or when it is set as the startup project in Visual Studio and debugged using IIS, it will call out to the SSO site and start the SSO flow. But when I try to run it through IIS without debugging, I get an error:
The string parameter 'namespaceName' cannot be null or empty.
The stack trace seems to indicate that something went wrong when trying to run the OWIN startup process.
[ArgumentException: The string parameter 'namespaceName' cannot be null or empty. Parameter name: namespaceName]
System.Web.UI.TagPrefixAttribute..ctor(String namespaceName, String tagPrefix) +3663848
System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs) +0
System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs) +48
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +846
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +144
Owin.Loader.DefaultLoader.SearchForStartupAttribute(String friendlyName, IList`1 errors, Boolean& conflict) +188
Owin.Loader.DefaultLoader.GetDefaultConfiguration(String friendlyName, IList`1 errors) +68
Owin.Loader.DefaultLoader.LoadImplementation(String startupName, IList`1 errorDetails) +89
Owin.Loader.DefaultLoader.Load(String startupName, IList`1 errorDetails) +30
Microsoft.Owin.Host.SystemWeb.OwinBuilder.GetAppStartup() +165
(Stack trace truncated, but nothing in the stack trace that hits the site's custom code)
Is there maybe something on the OwinContext that is set differently when the site is debugging vs IIS?
Thanks!

Invalid character in a Base-64 string for connection string

I have a Sql Server 2008 R2 connection string that looks like
<add name="DBConnectionString"
providerName="System.Data.SqlClient"
connectionString="Data Source=AYZ;Initial Catalog=AYZ;User ID=AYZ;Password=AYZ;"/>
When trying to create a new instance of SQLDatabase using EnterpriseLibrary.Data I get the above error.
connString =ConnectionStrings.ConnectionStrings["DBConnectionString"];
Database objDB = new SqlDatabase(connString);
connString has the following
Data Source=AYZ;Initial Catalog=AYZ;User ID=AYZ;Password=AYZ;
The detailed exception is as follows :
System.FormatException was unhandled by user code
Message=Invalid character in a Base-64 string.
Source=mscorlib
StackTrace:
at System.Convert.FromBase64String(String s)
at Microsoft.Practices.EnterpriseLibrary.Data.Database.DecryptConnectionString(String strEncyptConStr)
at Microsoft.Practices.EnterpriseLibrary.Data.Database..ctor(String connectionString, DbProviderFactory dbProviderFactory)
at Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase..ctor(String connectionString)
at ABC.GRC.DAL.CommonDAL..ctor() in D:\ABC\Projects\Right Price\ABC.GRC\ABC.GRC\ABC.GRC.DAL\CommonDAL.cs:line 31
at ABC.GRC.BLL.CommonBLL..ctor() in D:\ABC\Projects\Right Price\Syntel.GRC\Syntel.GRC\Syntel.GRC.BLL\CommonBLL.cs:line 14
at Global.Application_Error(Object sender, EventArgs e) in d:\ABC\Projects\Right Price\ABC.GRC\ABC.GRC\ABC.GRC.WEB\App_Code\Global.asax.cs:line 60
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Web.HttpApplication.RaiseOnError()
InnerException:
I think there is the problem
connString =ConnectionStrings.ConnectionStrings["ConnectionString"];
It should be
connString =ConnectionStrings.ConnectionStrings["DBConnectionString"];
Since you have key DBConnectionString in you configuration file not ConnectionString.
Useful link:
Read connection string from web.config

Grant ASP.NET MVC 3 website write access to ~/Content/uploads folder

I have an ASP.NET MVC 3 website that runs on the company intranet to which I want to add a page that can upload files to the server.
I am running the site on Windows Server 2012 with IIS 8.
IIS Config:
Application pool attributes:
.Net Framework v4.0
Managed Pipeline Mode: Integrated
Identity: LocalSystem
Under the site node, authentication is set as:
Windows Authentication: Enabled (Users must use their corporate Windows Accounts to log in)
All other Authentication including Anonymous Authentication set to Disabled.
Windows Permissions:
In the Content directory, I have granted all access permissions to the System, Admin and my User's account.
MVC Code:
The MVC Controller method that handles the file upload contains the following code:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
DateTime timestamp = DateTime.Today;
var path = Path.Combine(Server.MapPath("~/Content/uploads"), fileName);
if( !Directory.Exists(path))
Directory.CreateDirectory(path);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
When I try to upload a file using the above controller I get the following error:
Server Error in '/' Application.
Access to the path 'C:\Sites\ClosedBeta\Content\uploads\test.csv' is denied.
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.UnauthorizedAccessException: Access to the path 'C:\Sites\ClosedBeta\Content\uploads\test.csv' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
Source Error:
Line 34: if( !Directory.Exists(path))
Line 35: Directory.CreateDirectory(path);
Line 36: file.SaveAs(path);
Line 37: }
Line 38:
Source File: C:\Users\****\Documents\Visual Studio 2010\Projects\Solution\Project\Controllers\UploadTestController.cs Line: 36
Stack Trace:
[UnauthorizedAccessException: Access to the path 'C:\Sites\ClosedBeta\Content\uploads\test.csv' is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +10760710
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) +1352
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) +60
System.IO.FileStream..ctor(String path, FileMode mode) +55
System.Web.HttpPostedFile.SaveAs(String filename) +94
System.Web.HttpPostedFileWrapper.SaveAs(String filename) +9
Project.Controllers.UploadTestController.Upload(HttpPostedFileBase file) in C:\Users\****\Documents\Visual Studio 2010\Projects\Solution\Project\Controllers\UploadTestController.cs:36
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +214
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +253
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324
System.Web.Mvc.Controller.ExecuteCore() +106
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +48
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Any adivce would be apreciated
I think that the problem was simply that I needed to wait a bit for the permissions to take effect.
After Comming back to the same code the next day, it worked perfectly.
simply go though iis check is IISUSER and IUSR_ has permission to read and write
Generally plesk panel and cpanel add default permission to read list and write but in some cases something goes wrong and u need to setup the right permission.
So you have 2 way to achive your goal:
If you have access to iss do it by youself
or
Ask to your hosting company to setup write and read permission to this particular folder.

Basic post to test web service

I am working on form, which send input to webservice via post and display result. It must be simple, and it works fine on localhost. But when I try to use it agains live I have error 500.
Here is my code:
WebRequest request = WebRequest.Create("http://localhost:3192/WebServices/Export.asmx/" + uxAction.SelectedValue);
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(uxRequest.Text);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Flush();
requestStream.Close();
WebResponse response = request.GetResponse();
Stream newStream = response.GetResponseStream();
byte[] responseArray = new byte[response.ContentLength];
newStream.Read(responseArray, 0, (int)response.ContentLength);
newStream.Close();
uxResponse.Text = encoding.GetString(responseArray);
And here is information about error
Exception information:
Exception type: InvalidOperationException
Exception message: Request format is unrecognized for URL unexpectedly ending in '/GetProjectTypes'.
Request information:
Request URL: http://sitename.com/WebServices/Export.asmx/GetProjectTypes
Request path: /WebServices/Export.asmx/GetProjectTypes
User host address: 93.73.249.242
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 1
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: at System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath)
at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)
at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I also have http handler to access web services from javascript and this works fine:
<add verb="GET,HEAD,POST*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Here is my request data. Exception is same with or without it. Webservice do not have any parameters
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetProjectTypes xmlns="http://sitename.com/WebServices/Export.asmx" />
</soap:Body>
</soap:Envelope>
When we test webservice in browser, it adds methodname to url, but when we do post this is not needed.
I removed '/" + uxAction.SelectedValue' and everything is working fine now

Resources