web-dev-qa-db-fra.com

MVC5 redirige vers Login.aspx

Après la mise à niveau de MVC 4 vers MVC 5, mon application (lorsqu'elle est démarrée à partir de Visual Studio) génère l'erreur suivante. Il est également intéressant de noter que j'héberge les éléments MVC5 et WebAPI2 dans le même projet, car il peut y avoir des interférences. J'ai également installé le paquet nuget dotnetopenauth (que j'ai depuis supprimé):

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /login.aspx

Je ne sais pas trop pourquoi, car aucun attribut d’autorisation n’a été défini dans les filtres ni sur les contrôleurs.

Global.asax:

    public class MvcApplication : HttpApplication {

    protected void Application_Start() {
        IDependencyInjectionBuilder dependencyInjectionBuilder = new DependencyInjectorBuilder();
        var builder = new ContainerBuilder();

        builder.RegisterControllers(typeof(MvcApplication).Assembly);
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //For WebAPI dependency injection
        var injector = new AutofacDependencyInjector();
        dependencyInjectionBuilder.RegisterTypesAndInstances(injector, false, true);
        DependencyInjectionRegistration.RegisterServices(injector);

        builder.Update(injector.Container.ComponentRegistry);

        var autofacDependencyResolver = new AutofacDependencyResolver(injector.Container);
        DependencyResolver.SetResolver(autofacDependencyResolver);

        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(injector.Container); //For WebAPI dependency injection

        AreaRegistration.RegisterAllAreas();

        AutoMapperConfig.RegisterMappings(Mapper.Configuration);

        //Reference: http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2
        GlobalConfiguration.Configure(WebApiConfig.Register);

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        GlobalConfiguration.Configuration.EnsureInitialized();

#if DEBUG
        // Uncomment this line for the nhibernate profiler 
        // and add HibernatingRhinos.Profiler.Appender.dll
        // to the PD.UserInterfacePbj project references

       //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
#endif
    }
}

Racine Web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="PreserveLoginUrl" value="true" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
    <log4net>
        <appender name="NHProfAppender" type="HibernatingRhinos.Profiler.Appender.NHibernate.NHProfAppender, HibernatingRhinos.Profiler.Appender.NHibernateLog4Net">
            <sink value="tcp://127.0.0.1:56107" />
        </appender>
        <logger name="HibernatingRhinos.Profiler.Appender.NHibernate.NHProfAppender.Setup">
            <appender-ref ref="NHProfAppender" />
        </logger>
        <root>
            <priority value="ALL" />
            <appender-ref ref="ConsoleAppender" />
        </root>
    </log4net>
    <system.web>
        <customErrors mode="Off" defaultRedirect="~/Error/Index">
            <error statusCode="404" redirect="~/Error/Error404" />
        </customErrors>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime />
        <authentication mode="Windows" />
        <authorization>
            <deny users="?" />
        </authorization>
        <pages controlRenderingCompatibilityVersion="4.0">
            <namespaces>
                <add namespace="System.Web.Helpers" />
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Optimization" />
                <add namespace="System.Web.Routing" />
                <add namespace="System.Web.WebPages" />
                <add namespace="My.Localization" />
            </namespaces>
        </pages>
    </system.web>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <remove name="OPTIONSVerbHandler" />
            <remove name="TRACEVerbHandler" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
    </system.webServer>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-Microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" />
                    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="5.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Spatial" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.5.0.0" newVersion="5.5.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-3.3.1.4000" newVersion="3.3.1.4000" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
        <bytecode-provider type="null" />
        <!-- Important under Medium Trust -->
        <session-factory name="Stinky Pete">
            <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
            <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
            <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
            <property name="connection.connection_string"> ... </property>
            <mapping Assembly=" ... " />
        </session-factory>
    </hibernate-configuration>
    <system.net>
        <defaultProxy enabled="true" />
        <settings>
        <!--<servicePointManager checkCertificateRevocationList="true"/>-->
        </settings>
    </system.net>
    <uri>
        <!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names), which is necessary for OpenID urls with unicode characters in the domain/Host name. 
    It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. -->
        <idn enabled="All" />
        <iriParsing enabled="true" />
    </uri>
</configuration>

Vues Web.config:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="Host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <system.web.webPages.razor>
        <Host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Optimization"/>
                <add namespace="System.Web.Routing" />
                <add namespace="Infragistics.Web.Mvc"/>
            </namespaces>
        </pages>
    </system.web.webPages.razor>
    <appSettings>
        <add key="webpages:Enabled" value="false" />
    </appSettings>
    <system.web>
        <httpHandlers>
            <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
        </httpHandlers>
        <pages validateRequest="false" pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0,  Culture=neutral, PublicKeyToken=31BF3856AD364E35" pageBaseType="System.Web.Mvc.ViewPage,  System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0,  Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <controls>
                <add Assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
            </controls>
        </pages>
    </system.web>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
            <remove name="BlockViewHandler"/>
            <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
    </system.webServer>
</configuration>
25
Flea

J'ai pu résoudre le problème en ajoutant ce qui suit dans la section appSettings selon la réponse à à cette question .

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
37
Flea

De plus, la section Web.Config System.web NE devrait PAS contenir cette ligne:

<authentication mode="Forms" />

Et dans mon cas cela a fonctionné.

5
SvitlanaS

Si vous exécutez votre application localement et obtenez une erreur http 401, vous devrez peut-être modifier votre configuration IISExpress. Accédez à Documents> IISExpress> applicationhost.config

Assurez-vous que windowsAuthentication est activé:

             <windowsAuthentication enabled="true">
                <providers>
                    <add value="Negotiate" />
                    <add value="NTLM" />
                </providers>
            </windowsAuthentication>
2
jmyns

En plus des réponses ci-dessus, selon le modèle utilisé pour créer le projet, vous pouvez avoir Startup.Auth.cs dans le dossier App_Start avec le code suivant pouvant être commenté:

// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
     AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
     LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
0
pfeds