In web forms we can write this code above the page:
<%# Register Assembly="xxx.CaptchaGenerator"
Namespace="xxx.CaptchaGenerator" TagPrefix="mycaptcha" %>
Then it can be used:
<mycaptcha:CaptchaControl ID="ccJoin"
runat="server" CaptchaHeight="31" CaptchaLength="5" />
How can I do this in mvc3, razor? I use this syntax #Using xxx.CaptchaGenerator and add this lines in my web config :
<pages>
<namespaces>
<add namespace="xxx.CaptchaGenerator" />
<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.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
but it did not work.
You could add namespaces to the ~/Views/web.config, not ~/web.config. For example:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.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.Routing" />
<add namespace="xxx.CaptchaGenerator" />
</namespaces>
</pages>
</system.web.webPages.razor>
as i know cant use the server control in view(razorengine)..
you can use aspx file and then call it in your parent view with html.partial(aspx fileName)
i know this not a good solution and maybe not correct answer but its useful dear mohsen
شاید راه دیگه ایم باشه
Related
I've been trying to use RadUpload.Net2 from Telerik using a simple .aspx page, but i'm getting a null reference for the next line of code:
UploadedFile file = RadUploadContext.Current.UploadedFiles[File1.UniqueID];
when using the following controls:
<input id="File1" type="file" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="true" OnClick="Button1_Click"/>
<radUpload:RadProgressManager runat="server" ID="Radprogressmanager"/>
<radUpload:RadProgressArea ID="RadProgressArea1" runat="server" />
I'm using IIS 7.5 with the DefaultAppPool, .Net 4.0 Integrated. The WebConfig is as follows:
<configuration>
<appSettings>
<add key="Telerik.WebControls.RadControlsDir" value="~/Resources/RadControls/" />
<add key="Telerik.WebControls.RadUpload.TempFolder" value="D:\Projects\ODW\Temp\Upload" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="RadUpload.Net2, Version=2.4.1.0, Culture=neutral, PublicKeyToken=B4E93C26A31A21F0" />
<add assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
<pages enableEventValidation="false" validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
<httpRuntime maxRequestLength="30240" executionTimeout="10" />
<!--<httpModules>
<add name="RadUploadModule" type="Telerik.WebControls.RadUploadHttpModule, RadUpload.Net2, Version=2.3.0.0, Culture=neutral, PublicKeyToken=b4e93c26a31a21f0" />
</httpModules>
<httpHandlers>
<add verb="*" path="Telerik.RadUploadProgressHandler.aspx" type="Telerik.WebControls.RadUploadProgressHandler, RadUpload.Net2, Version=2.3.0.0, Culture=neutral, PublicKeyToken=b4e93c26a31a21f0" validate="false" />
</httpHandlers>-->
<trace enabled="false" pageOutput="false" requestLimit="40" localOnly="false" />
<authorization>
<allow users="*" />
</authorization>
<trust level="Full" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="RadUploadModule" type="Telerik.WebControls.RadUploadHttpModule, RadUpload.Net2, Version=2.4.1.0, Culture=neutral, PublicKeyToken=b4e93c26a31a21f0" preCondition="integratedMode" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="Telerik_RadUploadProgressHandler_ashx" verb="*" path="Telerik.RadUploadProgressHandler.aspx" type="Telerik.WebControls.RadUploadProgressHandler, RadUpload.Net2, Version=2.4.1.0, Culture=neutral, PublicKeyToken=b4e93c26a31a21f0" preCondition="integratedMode" />
</handlers>
</system.webServer>
</configuration>
The handler is registered in IIS. I've tried it on classic .Net app pools an it's still not working.
The RadUpload.Net2 is a very archaic control (pre-2007), you should be using the Telerik.Web.UI assembly if your project is on .NET 4
I have changed service providers, and since then as soon as i goto www.greptech.co.za i get the above error.
The service provider is using .NET 4.0 and does have the latest MVC3 installed and up to date.
What else can be the issue ? I have googled this, and i have done the above checks. The service provider doesnt know what else is wrong.
I havent changed my Web.config file, for it was working with my old service provider.
Site has been down for a long time now. Please can anyone assist
Here is my web.config file :
<?xml version="1.0" encoding="UTF-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<add name="MySqlServer" connectionString="Datasource=431.186.904.538;Port=3306;Database=grep;uid=user;pwd='XXXX';Allow User Variables=true;check parameters=false;logging=true" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="support#greptech.co.za">
<network host="mail.greptech.co.za" userName="support#greptech.co.za" password="XXXX" port="25" />
</smtp>
</mailSettings>
</system.net>
<appSettings>
<add key="ENV" value="PROD"/>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<!-- <customErrors mode="On"/> -->
<trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<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.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<customErrors mode="Off"/>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
<defaultDocument>
<files>
<clear />
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
<add value="default.aspx" />
<add value="index.php" />
</files>
</defaultDocument>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Ok, thanks for the reply .. Here is the ~/Views/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=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.net >
<mailSettings>
<smtp deliveryMethod="Network" from="support#greptech.co.za">
<network host="mail.greptech.co.za" userName="support#greptech.co.za" password="XXXX" port="25" />
</smtp>
</mailSettings>
</system.net>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.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.Routing" />
</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>
<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=3.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>
I ended up going back to original Service Provider
I think I might have an idea what's going on looking at the debug output - this part doesn't look right:
Line 12: namespace ASP {
Line 13: using System;
Line 14: using System.Collections.Generic;
Line 15: using System.IO;
Line 16: using System.Linq;
Line 17: using System.Net;
Line 18: using System.Web;
Line 19: using System.Web.Helpers;
Line 20: using System.Web.Security;
Line 21: using System.Web.UI;
Line 22: using System.Web.WebPages;
Line 23: using System.Web.WebPages.Html;
Line 24: using WebMatrix.Data;
Line 25: using WebMatrix.WebData;
Line 26:
Line 27:
Line 28: public class _Page_index_cshtml : System.Web.WebPages.WebPage {
First your page inherits WebPages.WebPage - how did that happen? Then above.. notice the lack of System.Web.Mvc ? That's the reason you also get errors for missing 'BeginForm' and 'Partial' methods, because they are all part of the System.Web.Mvc namespace.
Here's how a fresh MVC 3 project output looks for me:
Line 12: namespace ASP {
Line 13: using System;
Line 14: using System.Collections.Generic;
Line 15: using System.IO;
Line 16: using System.Linq;
Line 17: using System.Net;
Line 18: using System.Web;
Line 19: using System.Web.Helpers;
Line 20: using System.Web.Security;
Line 21: using System.Web.UI;
Line 22: using System.Web.WebPages;
Line 23: using System.Web.Mvc;
Line 24: using System.Web.Mvc.Ajax;
Line 25: using System.Web.Mvc.Html;
Line 26: using System.Web.Routing;
Line 27:
Line 28:
Line 29: public class _Page_Views_Home_Index_cshtml : System.Web.Mvc.WebViewPage<dynamic> {
The config you listed above is perfectly fine. However the config in /Views is what affects the generation of views and my best guess is there's something wrong there. This is the bit that I noticed makes or breaks the view output (namespaces here are directly reflected in the generated code, similar to Problem recognizing html helpers in asp.net mvc 3 razor ):
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.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.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
At this point it seems like a good idea if you can also add the ~/Views/Web.config in case this is not the issue.
Ended up going back to original Service Provider
I am making a Helper with razor generator to build a cutom control in which there will be two radio buttons (yes/no)
I want to use Html.BeginForm for this.
But can't do it.
Do you know how to do it or another way to do it ?
Thanks.
Edit :
When I put this code
#using (Html.BeginForm()) {
<input type="radio"/>
<input type="radio"/>
}
I get this error
'System.Web.WebPages.HtmlHelper' does not contain a definition for BeginForm and no extension method
'BeginForm' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper'could be found
It's most likely a namespacing or reference issue.
First, check to make sure that System.Web.WebPages shows up in your project references. Then add
#using System.Web.WebPages
to the top of your view. If that fixes it, you can move the reference into the web.config per this answer on the same type of topic
Add this code to your helper function when your helper functions are located in the App_Code folder.
var Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;
var Ajax = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Ajax;
Don't forget to include the right namespaces in the file: #using ....
For me it was a missing namespace, yes, but not the one mentioned by eouw0o83hf:
#using System.Web.Mvc.Html;
Please post your code when you ask a question so we can see what you're doing wrong. Try this:
#using (Html.BeginForm()) {
<input type="radio"/>
<input type="radio"/>
}
I ran into the same issue and just solved it. I changed version in the web.config file under the views folder.
Here is my previous code
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, **Version=5.0.2.2**, 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="CMSSol" />
</namespaces>
</pages>
and here is my new code
<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="CMSSol" />
</namespaces>
</pages>
I am having my mvc project that is working fine on my local machine. However, once posted on the server, the users can`t access the login the secong time they are trying to access the website. They have to delete the cookies. Why is that so? How can I correct that?
Global.asax.cs
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.cookies[FormsAuthentication.FormsCookieName].Value);
args.user = new MyProject.Web.UI.Classes.UserPrincipal(GetUserFromCache(ticket.Name))
SourceFile: c:\Myproject\Code\MvcUI\Global.asax.cs
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
{
if (FormsAuthentication.CookiesSupported)
{
if (null != Request.Cookies[FormsAuthentication.FormsCookieName])
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
args.User = new MyProject.Web.UI.Classes.UserPrincipal(GetUserFromCache(ticket.Name));
}
}
else
throw new HttpException("Cookieless Forms Authentication is not supported for this application.");
}
public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs args)
{
string username = args.Identity.Name.Substring(args.Identity.Name.IndexOf("\\") + 1);
Myproject.API.User user = GetUserFromCache(username);
if (null == user)
throw new HttpException("User could not be found.");
args.User = new MyProject.Web.UI.Classes.UserPrincipal(user);
}
AccountController
[HttpPost]
public bool LogOn(string userName, string password, string returnUrl, bool rememberMe = false)
{
MyProject.API.User user = MyProject.API.User.Load(userName);
string errorMessage = "Your user name and/or password is incorrect.";
if (null != user && user.IsValidPassword(password))
{
user.LastLoginDate = DateTime.Now;
user.Save();
FormsAuthentication.SetAuthCookie(userName, rememberMe);
return true;
}
else
throw new Exception(errorMessage);
}
web.config
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.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=3.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.Routing" />
<add namespace="MvcUI.HtmlHelpers" />
<add namespace="MyProject.API" />
<add namespace="MvcUI.Models" />
</namespaces>
</pages>
</system.web.webPages.razor>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
</assemblies>
<buildProviders>
<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</buildProviders>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<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.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
<httpHandlers>
<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
validate="false" />
</httpHandlers>
</system.web>
<nhibernate>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect"/>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<add key="hibernate.connection.connection_string" value="Server=.\SQLEXPRESS;Database=myDatabase;User=me;Pwd=password;"/>
<add key="hibernate.show_sql" value="false"/>
</nhibernate>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
account Model
public interface IFormsAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
The error message points to the Gloabal.asax.cs file and shown above.
Error message:
I have also included a machine key generated but it has not solved the problem,
Based on your feedback, the reason you are experiencing that error may be due to the fact you are using an auto-generated machineKey for your application (also possibly in multiple machines/app pools or even in one app pool that recycles too frequently).
Please make sure to check this one out.
Have you applied this patch?
I see you don't have ticketCompatibilityMode set as .net 4 has changed the way encryption works.
<forms
loginUrl="/Login.aspx"
timeout="2880"
ticketCompatibilityMode="Framework20"
domain="domain.com"/>
Check that you have the same machineKeys on both systems. Make sure you also apply that patch.
Because the patch modifies the encryption/signing behavior of certain features in ASP.NET, it is important that you apply it to all machines in a web-farm. If you have a mix-match of patched/un-patched systems you’ll have forms-authentication, webresource.axd, and scriptresource.axd requests succeed/fail depending on which server they hit in the farm (since the encryption used would be different across them).
I assume your users are redirected to somewhere upon reaching the login page if the request is authenticated and thus they can't access the login page after the first successful login.
If this is the case, you may want to force your users to sign out upon reaching the login page, on the first load of the page. For example (Razor syntax, C#):
#if (!IsPost && Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
On the GET (not post) of LogOn action method. Check if user is authenticated and log out if so.
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
Thanks to all of you for having tried to reply to the question. Indeed they were all helpful. I solved the problem myself by adding a machinekey to the wenconfig, as well as a form name had to be there. without te form name, even the machine key was not useful
When my Razor view calls #Html.OpenIdSelector(... I get an InvalidOperationException:
The current IHttpHandler is not one of
types: System.Web.UI.Page,
DotNetOpenAuth.IEmbeddedResourceRetrieval.
An embedded resource URL provider must
be set in your .config file.
What exactly should I set in the config file?
Just NuGet the DotNetOpenAuth package. It will setup everything you need in your config file:
Right click on the References of your web project in the solution explorer
Add Library Package Reference...
Click on the Online tab.
In the search box type dotnetopenauth
Click Install
Everything will be automatically setup and the correct assemblies will be downloaded from the internet and added as reference.
Here's how the web.config file looks like after performing this:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" />
</configSections>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<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.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
<legacyHMACWarning enabled="0" />
</runtime>
<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>
<system.net>
<defaultProxy enabled="true" />
<settings>
<!-- This setting causes .NET to check certificate revocation lists (CRL)
before trusting HTTPS certificates. But this setting tends to not
be allowed in shared hosting environments. -->
<!--<servicePointManager checkCertificateRevocationList="true"/>-->
</settings>
</system.net>
<dotNetOpenAuth>
<!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. -->
<!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ -->
<openid>
<relyingParty>
<security requireSsl="false" />
<behaviors>
<!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
with OPs that use Attribute Exchange (in various formats). -->
<add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" />
</behaviors>
</relyingParty>
</openid>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
</dotNetOpenAuth>
</configuration>
UPDATE:
You could implement a custom resource retrieval provider:
public class CustomResourceProvider : IEmbeddedResourceRetrieval
{
public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
{
return new Uri("http://www.google.com");
}
}
and then register it in web.config:
<dotNetOpenAuth>
<webResourceUrlProvider type="AppName.CustomResourceProvider, AppName" />
...
</dotNetOpenAuth>
But I would recommend you using the openid-selector library for generating login forms.
I came across this problem when I was trying to get the NerdDinner OpenID working for MVC3/razor. The solution that has worked for me is:
Create this class in your solution: (this was found in one of the NerdDinner builds - http://nerddinner.codeplex.com/SourceControl/changeset/view/55257#1328982 (thanks to JasonHaley)
for some reason, this file isn't in the latest build for NerdDinner MVC3/Razor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth;
namespace <Your App>.Services
{
public class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval
{
private static string pathFormat = "{0}/{1}/Resource/GetWebResourceUrl?assemblyName={2}&typeName={3}&resourceName={4}";
//private static string pathFormat = "{0}/Resource/GetWebResourceUrl";
public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
{
if (manifestResourceName.Contains("http"))
{
return new Uri(manifestResourceName);
}
else
{
var assembly = someTypeInResourceAssembly.Assembly;
// HACK
string completeUrl = HttpContext.Current.Request.Url.ToString();
string host = completeUrl.Substring(0,
completeUrl.IndexOf(HttpContext.Current.Request.Url.AbsolutePath));
var path = string.Format(pathFormat,
host,
HttpContext.Current.Request.ApplicationPath.Substring(1),
HttpUtility.UrlEncode(assembly.FullName),
HttpUtility.UrlEncode(someTypeInResourceAssembly.ToString()),
HttpUtility.UrlEncode(manifestResourceName));
return new Uri(path);
}
}
}
}
Then in your web.config, add this line:
<webResourceUrlProvider type="<Your App>.Services.EmbeddedResourceUrlService, <Your App>" />
just put in the DotNetOpenAuth section
you will also need this route set up: ( Html.OpenIdSelectorScripts helper method throwing NullReferenceException )
routes.MapRoute(
"OpenIdDiscover",
"Auth/Discover"
);