Razor create link to route - asp.net-mvc-4

I've just installed Elmah in my MVC application. It magically added a route in Web.config:
<add key="elmah.mvc.route" value="elmah" />
Which I can access through:
localhost/elmah
How can I create a link to this action in Razor?

#Html.RouteLink("elmah")
or
elmah

Related

MVC4 Windows Authentication Redirect to Account/Login

I am setting up Windows Authentication in an MVC 4 application using Visual Studio 2013 and using the IIS Express Development Server. However, I get redirected to /Account/Login (as if I were using forms authentication).
I have no reference to WebMatrix in my bin folder (or anywhere) as described here: ASP.NET MVC3 and Windows Auth on IIS keeps redirecting to /Account/Login.
I have added these entries to appSettings in the web.config as suggested by this post:
MVC5 Redirects to Login.aspx when using Windows Authentication
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
Here is what I have done so far:
Added windows authentication to system.web.
<authentication mode="Windows"/>
Added the [Authorize] attribute to my controller. I have also tried using the authorization tag in the web.config instead of the attribute on the controller (deny users="?"). The results are the same.
For the Development Server settings in my project I changed these settings:
Anonymous Authentication = Disabled
Windows Authentication = Enabled
I can find no reference to FormsAuthentication. I can't figure out why it still redirects to a non-existent login page.
When the project was created it may have been done using a template that added Startup.Auth in the App_Start folder in your project. (The default template uses Individual User Accounts if you did not change it to windows authentication as the Authentication method in the create new ASP.Net Project dialog)
Try commenting out these lines if they are present
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Or if you have not added anything to this file you could remove it completely and the call to it
ConfigureAuth(app);
found in the startup.cs in the root of the project
Now most of the account controller is no good to use if this case so be prepared to clean that up also.
This line is important and correct in the web config
<authentication mode="Windows"/>
these lines are probably not directly related to the issue and can be removed
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
The other development settings are also correct.

BetterCMS with MVC4 Simple membership provider

I've set up BetterCMS in my MVC4 app. and it seems like it's working except I can't figure out how to configure it to use Simple Membership Provider that comes with MVC4 internet app.
http://www.devbridge.com/articles/better-cms-for-developers
please help!. thanks
EDIT: I've created my MVC4 app using Internet Template which comes with Simple Membership Provider already configured and working. I would like to have those members I've "registered" as BetterCMS users.
If you want to use Better CMS, use BetterCms.Module.Users module from NuGet with it's role provider, membership provider and UI for managing users. How to setup users module, you can read in BetterCMS wiki pages on Github
But if you still wish to use Better CMS with Simple Membership Provider, follow steps below. That's what I've done and it works fine for me.
Create an MVC 4 solution and select Internet template
Run the application and create a user
Install BetterCMS by following steps, explained in Better CMS github wiki, section "Project Setup".
Do not forget to remove default routes registration (routes.MapRoute(name: "Default" ....) from RouteConfig class.
Register routes below in the RouteConfig class. After that MVC home page can be reached by URL /home/:
routes.MapRoute("mvc-account-controller", "account/{action}/{id}", new
{
area = string.Empty,
controller = "Account",
action = "Login",
id = UrlParameter.Optional
});
routes.MapRoute("mvc-home-controller", "home/{action}/{id}", new
{
area = string.Empty,
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
Add role provider and membership provider to web.config (solution found here):
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
Add LazyInitializer to global.asax as explained here
Remove [InitializeSimpleMembership] attribute from AccountController, because database connection is already initialized. Also, SMP2.Filters.InitializeSimpleMembershipAttribute class can also be deleted.
Create an admin role and assign it for user (it can be done using ASP.NET Configuration or directly in the database). For example, create role with name "Role1".
There are two ways to set up administrator roles for the user (you can read more in the Better CMS Github Wiki, topic "CMS configuration"):
Set your created role as full access role (cms.config, security section's fullAccessRoles attribute set to fullAccessRoles="Role1" )
Add roles mappings in the cms.config's security section:
<customRoles>
<add permission="BcmsEditContent" roles="Role1" />
<add permission="BcmsPublishContent" roles="Role1" />
<add permission="BcmsDeleteContent" roles="Role1" />
<add permission="BcmsAdministration" roles="Role1" />
</customRoles>
Run application. Go to url /account/login and log-in using admininstrator account, which was created in the 2nd step. Then go back to any CMS page, for example, root page (/).
Here you go, you're connected as administrator and CMS sidebar is availabe for web site editing.

Using created Login Page for authentication in ASP.NET MVC 4

I want to use my own Login Page for authentication, but it is giving me this error
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: /Account/PasswordLock
Anyone knows why?Here is my code, I created a new page called PasswordLock.aspx with a login tool in it. everything works fine with the original Login form, but not mine own.
<authentication mode="Forms">
<forms loginUrl="~/Account/PasswordLock" timeout="2880" />
</authentication>
while this will work fine
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
Thanks
In ASP.NET MVC, your URLs don't map to files; they map to actions. So, having a file at ~/Accounts/PasswordLock.aspx doesn't help. What you need is a route for that URL. The routes are usually set up in a file called RouteConfig, under the App_Start folder, executed by the Application_Start() method in Global.asax. The usual default route looks like this:
routes.MapRoute(
name: "default",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
This means that a URL that goes www.example.com/Accounts/PasswordLock will map to a controller called AccountsController, and a method on that controller called PasswordLock. This method should return a View which by default will be called PasswordLock.cshtml. Note that the new Razor v2 view engine uses .cshtml files rather than .aspx.
This is all pretty fundamental to ASP.NET MVC programming; it sounds rather like you're jumping in blindly. I'd strongly advise reading the tutorials at www.asp.net/mvc, particularly the ones on controllers and routing.

How do I use windows authentication with roles with Hot Towel?

I can spin up a standard asp.net mvc 4 intranet project and decorate the controller or methods with things like:
[System.Web.Mvc.Authorize(Roles = "MyApp Users")]
I have tested it and it will work perfectly (since my domain account is a member of the "MyApp Users" in Active Directory)
However my problem/question is how do I get the same type of behavior for a "Hot Towel" application? I try decorating my breeze controller, HotTowel Controller, or any method with the same attribute and I can never authenticate... what gives?
Your help is greatly appreciated.
Finally figured it out. I hope this is of use to others.
First you must set the WindowsProvider as your roleManager like so:
<roleManager defaultProvider="WindowsProvider"
enabled="true"
cacheRolesInCookie="false">
<providers>
<add
name="WindowsProvider"
type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
Then you will be able to check the roles for the user [using Roles.IsUserInRole()], and more specifically to this question use the authorize attribute. The only thing is that you will have to include the domain in the authorize attribute, like so:
[System.Web.Mvc.Authorize(Roles = "YourDomain\\MyApp Users")]
And now everything works as you would expect.

Running WebApi alongside MVC project in Azure

I have a solution with an MVC project and also a separate Web Api project. I have been working on the the MVC portion and have had it hosted as a web role in a cloud service project.
Now I need to build on the Web Api. Running the solution as is in the azure emulator I'm unable to hit my Web Api controller, I get a 404 Not Found.
What steps do I need to take after creating the WebApi project in the solution in order to enable my MVC project alongside it to hit the Api controller using a jQuery ajax call (from the MVC project)?
Note: The portion of the application that will be consuming the Api is in a subdomain (ex "consumingapp.myapplication.com/api/Values". I don't know if that makes any difference.
Ok here are the steps to run MVC and WebApi side by side in Azure under a single web role:
Add only the MVC project as a Web Role in the Cloud Service project.
Open ServiceDefinition.csdef an configure as follows:
<Sites>
<Site name="Web" physicalDirectory="..\..\..\Application.Web">
<Bindings>
<Binding name="Endpoint1" endpointName="Endpoint1" />
</Bindings>
</Site>
<Site name="Web.Api" physicalDirectory="..\..\..\Application.Web.Api">
<Bindings>
<Binding name="Endpoint1" endpointName="Endpoint1" hostHeader="api.myapplication.com"/>
</Bindings>
</Site>
</Sites>
Note:
The physical directory is relative to the definition file that is deployed to CloudProject\bin\release so you need to back track 3 nodes to get to the solution folder. Also I had some trouble with this trying to run the project it would automatically switch the physicalDirectory back to a bad path. To fix that I right clicked the cloud project > Project Dependencies > make sure both projects are checked off. Also make sure to save and close all instances of the text editor for the definition file then Rebuild and finally Run. Seems like some kind of bug that was driving me nuts and eventually disappeared.
Configure your host files to allow for local testing using the emulator:
127.0.0.1 myapplication.com api.myapplication.com
To use this .NET cors implementation run the following Nuget command on your WebApi project:
Install-Package Thinktecture.IdentityModel
Add the following class (taken from the post) to your WebApi project:
public static class CorsConfig
{
public static void RegisterCors(HttpConfiguration httpConfiguration)
{
WebApiCorsConfiguration corsConfig = new WebApiCorsConfiguration();
corsConfig.RegisterGlobal(httpConfiguration);
corsConfig
.ForResources("Values") //Controller nae
.ForOrigins("http://myapplication.com", "myapplication.com:81")
.AllowAll();
}
}
Call RegisterCors() from Application_Start()
Make sure you Web.config in the WebApi project has OPTIONS verb for the ExtensionlessUrlHandler:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Make cross-origin request to hit your api controller:
$.ajax({ url: "http://api.myapplication.com/api/Values", ... })
And Viola!
Hope that helps others