Publishing my API project in another IIS - asp.net-mvc

I've published my API project several times and it doesn't have any problem. but when I publish the same publish files in one of my server's IIS it rise a error about one of my controllers.
I've checked it, it works properly in my local and another IIS.
This XML file does not appear to have any style information associated
with it. The document tree is shown below. An error
has occurred. An error occurred when
trying to create a controller of type 'CityController'. Make sure that
the controller has a parameterless public constructor.
System.InvalidOperationException
at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage
request, HttpControllerDescriptor controllerDescriptor, Type
controllerType) at
System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage
request) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()
An error has
occurred. Type
'Jabama.Web.API.Controllers.CityController' does not have a default
constructor
System.ArgumentException
at System.Linq.Expressions.Expression.New(Type type) at
System.Web.Http.Internal.TypeActivator.Create[TBase](Type
instanceType) at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage
request, Type controllerType, Func`1& activator) at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage
request, HttpControllerDescriptor controllerDescriptor, Type
controllerType)
I checked all of the cityController's dependencies, there isn't any problem in it.

I finally found what's wrong. when I published the API project, it didn't publish the Microsoft.SqlServer.Type dll in it's bin folder.I copyed the dll manualy to that IIS and it's work but I don't know why it was giving me such an error! and even yet now what was wrong with my new IIS which the API didn't work without this dll, and the other IIS worked without this even without copying it!

Related

WebSecurity.InitializeDatabaseConnection method can be called only once

I'm trying Windows Azure to host an MVC4 web application.
I've created a test app, using VS2012 MVC4 internet application template and added a custom Model and Controller to it.
I've published it on Azure and managed to get 'update-database' apply migrations to the Azure Database.
When i try the app locally, but using the Azure SQL database, it works fine.
I can login/register and use my test controller.
When i try the app online, i can use the test controller but login or register links give the following exception:
Server Error in '/' Application.
The "WebSecurity.InitializeDatabaseConnection" method can be called only once.
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.InvalidOperationException: The "WebSecurity.InitializeDatabaseConnection" method can be called only once.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The "WebSecurity.InitializeDatabaseConnection" method can be called only once.]
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +123
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +52
MembershipTest2.Filters.SimpleMembershipInitializer..ctor() +193
Do you have any idea where that comes from ?
If i debug (the local version), this method is only called once.
Thanks.
You could try encapsulating the call(s) to that method to ensure it's not called more then once
if (!WebMatrix.WebData.WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection(...);
}
in my case I had both
(in web.config)
<add key="enableSimpleMembership" value="true" />
and
(in _ViewStart.cshtml)
WebSecurity.InitializeDatabaseConnection("club", "Account", "UserID", "UserName", autoCreateTables: true);
Solution: it seems you cannot have both, so remove one
Does the following SO discussion help you?
Cannot seed Users & Roles
I did find the following article helped me lot to use newer MVC4 & EF together with Simple Membership Provider so if you haven't read it please take a look:
SimpleMembership, Membership Providers, Universal Providers and the new ASP.NET 4.5 Web Forms and ASP.NET MVC 4 templates

Why does XDocument.Load throw exception when ELMAH is enabled?

I have the following code that retrieves a link to the latest post from the blog subsite:
XDocument doc = XDocument.Load("http://www.mysite.com/blog/syndication.axd");
XElement node = doc.Descendants("item").FirstOrDefault();
string text = node.Element("title").Value;
string uri = node.Element("link").Value;
The code always worked fine. This week I added ELMAH.MVC via NuGet as a Package Reference. As soon as I deploy the web.config file with the added ELMAH sections, I get the following error:
System.Web.HttpException (0x80004005): Error executing child request for handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.
---> System.Net.WebException: The remote server returned an error: (500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponse()
at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlReaderSettings.CreateReader(String inputUri, XmlParserContext inputContext)
at System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
at System.Xml.Linq.XDocument.Load(String uri, LoadOptions options)
If I put the old web.config file back, the error goes away.
Any idea why adding ELMAH would cause XDocument.Load to fail?
You need to look at your ASP.Net site and find the server-side error.

WCF NullReferenceException

I'm hosting an ASP.NET MVC site on Winhost and recently added a WCF data service for users providing feedback. The service works fine from my local machine, but when I deploy it I get the following System.NullReferenceException returned in Fiddler whenever I try to save an entry to the service:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<code></code>
<message xml:lang="en-US">An error occurred while processing this request.</message>
<innererror>
<message>Object reference not set to an instance of an object.</message>
<type>System.NullReferenceException</type>
<stacktrace> at System.Data.Services.Providers.ObjectContextServiceProvider.SetValue(Object targetResource, String propertyName, Object propertyValue)
at System.Data.Services.Serializers.Deserializer.SetPropertyValue(ResourceProperty resourceProperty, Object declaringResource, Object propertyValue, ContentFormat contentFormat, IDataService service)
at System.Data.Services.Serializers.PlainXmlDeserializer.ApplyProperty(XmlReader reader, String propertyName, ResourceType resourceType, Object resource)
at System.Data.Services.Serializers.PlainXmlDeserializer.ApplyContent(XmlReader reader, ResourceType resourceType, Object resource)
at System.Data.Services.Serializers.PlainXmlDeserializer.ApplyContent(Deserializer deserializer, XmlReader reader, ResourceType resourceType, Object resource, EpmAppliedPropertyInfo propertiesApplied, Int32 currentObjectCount)
at System.Data.Services.Serializers.SyndicationDeserializer.ApplyProperties(SyndicationItem item, ResourceType resourceType, EpmAppliedPropertyInfo propertiesApplied, Object resource)
at System.Data.Services.Serializers.SyndicationDeserializer.CreateObject(SegmentInfo segmentInfo, Boolean topLevel, SyndicationItem item)
at System.Data.Services.Serializers.SyndicationDeserializer.CreateSingleObject(SegmentInfo segmentInfo)
at System.Data.Services.Serializers.Deserializer.ReadEntity(RequestDescription requestDescription)
at System.Data.Services.Serializers.Deserializer.HandlePostRequest(RequestDescription requestDescription)
at System.Data.Services.DataService`1.HandlePostOperation(RequestDescription description, IDataService dataService)
at System.Data.Services.DataService`1.ProcessIncomingRequest(RequestDescription description, IDataService dataService)
at System.Data.Services.DataService`1.HandleNonBatchRequest(RequestDescription description)
at System.Data.Services.DataService`1.HandleRequest()</stacktrace>
</innererror>
</error>
Turn on tracing both on the server and on the client (see http://msdn.microsoft.com/en-us/library/ms733025.aspx), then use SvcTraceViewer (http://msdn.microsoft.com/en-us/library/ms732023.aspx). It will usually give you a more detailed exception.
My problem turned out to be 2 issues:
My site reroutes Url's for all GET requests to lower case. ODATA queries are case sensitive. This was causing me trouble with diagnosing the problem but wasn't causing the POST issue. Removing this for my service uri helped me identify the real problem.
The real issue was that my DataContext for my POCO entities had proxy generation enabled.
Here's a lengthier description of how I found the problem in case it helps anyone debug a similar issue:
Per Dan's suggestion, I enabled tracing to see if I could get any additional details. This showed me that I was getting a System.ServiceModel.CommunicationObjectAbortedException. I searched for the cause of this for a while with no success.
Next, I set my EntitySetRights for my DataService to EntitySetRights.All to see if I could determine the error by attempting to read my entity set (note that in my case this is a temporary change for debugging).
static public void InitializeService(DataServiceConfiguration config) {
...
config.SetEntitySetAccessRule("myentityset", EntitySetRights.All);
...
}
I then queried the service http://mydomain.com/myservice.svc/myentityset and received the following error:
Resource not found for the segment 'myentityset'
This turned out to be due to my site forcing all urls to lower case (apparently ODATA queries are case sensitive). My entity set is named something like 'MyEntitySet', but it was being queried as 'myentityset' Once I disabled this for my service url, I received an error similar to the following:
Internal Server Error. The type 'System.Data.Entity.DynamicProxies.myentity_XXXX' is not a complex type or an entity type
Looking up this error led me to this link identifying my core problem. The problem is with POCO Entity Generation for DataServices. In order to fix the problem ProxyCreationEnabled needs to be set to false. I added the following method to my T4 template that generates my ObjectContext.
<#+
private void WriteProxyCreation()
{
#>
this.ContextOptions.ProxyCreationEnabled = false;
<#+
}
#>
I then added a call to my method in each of the constructors similar to the following:
public <#=code.Escape(container)#>()
: base(ConnectionString, ContainerName)
{
<#
WriteLazyLoadingEnabled(container);
WriteProxyCreation();
#>
}

ASP.Net MVC, JS injection and System.ArgumentException - Illegal Characters in path

In my ASP.Net MVC application, I use custom error handling.
I want to perform custom actions for each error case I meet in my application.
So I override Application_Error, get the Server.GetLastError();
and do my business depending on the exception, the current user, the current URL (the application runs on many domains), the user IP, and many others.
Obviousely, the application is often the target of hackers.
In almost all the case it's not a problem to detect and manage it, but for some JS URL attacks, my error handling does not perform what I want it to do.
Ex (from logs) :
http://localhost:1809/Scripts/]||!o.support.htmlSerialize&&[1
When I got such an URL, an exception is raised when accessing the ConnectionStrings section in the web.config, and I can't even redirect to another URL.
It leads to a "System.ArgumentException - Illegal Characters in path, etc."
The screenshot below shows the problem :
http://screencast.com/t/Y2I1YWU4
An obvious solution is to write a HTTP module to filter the urls before they reach my application, but I'd like to avoid it because :
I like having the whole security being managed in one place (in the Application_Error() method)
In the module I cannot access the whole data I have in the application itself (application specific data I don't want to debate here)
Questions :
Did you meet this problem ?
How did you manage it ?
Thanks for you suggestions,
Mose
PS : here is the stack trace :
System.ArgumentException: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path)
at System.IO.Path.Combine(String path1, String path2)
at System.Web.Configuration.UserMapPath.GetPhysicalPathForPath(String path, VirtualDirectoryMapping mapping)
at System.Web.Configuration.UserMapPath.GetPathConfigFilename(String siteID, VirtualPath path, String& directory, String& baseName)
at System.Web.Configuration.UserMapPath.MapPath(String siteID, String path)
at System.Web.Hosting.HostingEnvironment.MapPathActual(VirtualPath virtualPath, Boolean permitNull)
at System.Web.Hosting.HostingEnvironment.MapPathInternal(VirtualPath virtualPath, Boolean permitNull)
at System.Web.CachedPathData.GetPhysicalPath(VirtualPath virtualPath)
at System.Web.CachedPathData.GetConfigPathData(String configPath)
at System.Web.CachedPathData.GetVirtualPathData(VirtualPath virtualPath, Boolean permitPathsOutsideApp)
at System.Web.HttpContext.GetFilePathData()
at System.Web.HttpContext.GetConfigurationPathData()
at System.Web.Configuration.RuntimeConfig.GetConfig(HttpContext context)
at System.Web.HttpContext.get_ImpersonationToken()
at System.Web.ClientImpersonationContext.Start(HttpContext context, Boolean throwOnError)
at System.Web.HttpApplication.ThreadContext.Enter(Boolean setImpersonationContext)
at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
at System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(Exception error)

2 asp.net mvc sites conflicting with each other

i have deployed an asp.net mvc site a few days ago and everything is going fine. I just deployed a second website (totally unrelated)
i just went to the first website and i am now getting an error below. Can anyone help me determine what is going on. I dont understand why they would know anything about each other.
The controller name 'Home' is ambiguous between the following types:
Site.netmvc.Controllers.HomeController
SalemGolf.Controllers.HomeController
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.InvalidOperationException: The controller name 'Home' is ambiguous between the following types:
Site.netmvc.Controllers.HomeController
SalemGolf.Controllers.HomeController
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The controller name 'Home' is ambiguous between the following types:
Site.netmvc.Controllers.HomeController
SalemGolf.Controllers.HomeController]
System.Web.Mvc.DefaultControllerFactory.GetControllerTypeWithinNamespaces(String controllerName, HashSet`1 namespaces) +417
System.Web.Mvc.DefaultControllerFactory.GetControllerType(String controllerName) +286
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +57
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase h
Make sure you don't have the assembly of the other site in your Bin directory.

Resources