You can use the system tray IIS Express icon to quit instances started using Powershell or command prompt. You can also type a the letter Q at the command prompt that gets spawned.
Wednesday, August 22, 2018
Running IISExpress from the command line or Powershell
You can use the system tray IIS Express icon to quit instances started using Powershell or command prompt. You can also type a the letter Q at the command prompt that gets spawned.
Saturday, May 20, 2017
Securing your ASP.NET MVC website Checklist
Add headers for all requests
<remove name="X-AspNetMvc-Version" />
<remove name="X-Powered-By" />
<remove name="Server" />
<add name="X-Frame-Options" value="DENY" />
<add name="Referrer-Policy" value="no-referrer" />
Require Strong Passwords
Remove ASP.NET Technology Headers
In Global.asax add the following to the Application_Start() event.
MvcHandler.DisableMvcResponseHeader = true;
You will also need to add the following to the web.config
<system.web>
<httpRuntime targetFramework="4.5.2" enableVersionHeader="false" />
</system.web>
Remove Server Info from headers
Also read through security issues that require reviewing your code and maybe some knowledge of how your application is written.
Restrict origin of anything loaded
There is a nuget package that does some of this. This looks to be a better choice as it is per controller, etc and explains how to use it.
X-Frame-Options
MVC5 will add in the X-Frame-Option by default. If you want to remove it and make it DENY you will need to add the following line to your Application_Start() method in the Global.asax.cs.System.Web.Helpers.AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
Thursday, May 18, 2017
OWASP Top 10 Security for ASP.NET tips you may not know about
SQL Injection
Havij for testing for SQL Injection on a web urlEncoding output
Use the appropriate encoding (escaping character or character sequences) for the context you are using the input.Use AntiXssEncoder.HtmlEncode() to HTML encode input when using web forms. (Available in NuGet or .NET 4.5). For example, use this before rendering user input what to the screen. <%: %> Syntax will automatically encode it.
ASP.NET MVC Razor automatically encodes for HTML unless you tell it not to. For example, on Model/ViewModel add the [AllowHtml] attribute to the property you want to allow.
Use Microsoft.Security.Application.Encoder.JavaScriptEncode() to encode input for JavaScript. For example taking input and assigning to a JavaScript variable.
You can turn off request validation at the site level (web.config) or the page level. See here for more details.
Hiding Payload
Url encoding can be used by hackers to get around XSS detectors and make the payload unclear to the average user. Another approach is to use a url shortener like tinyurl.com.Session Persistence
Don't use the url for any sensitive information since they are in web logs, browser history, etc. A session id is definitely sensitive information that can allow someone else to be you while that session is still active. Cookies are a much safer place to pass and persist session ids. The only downside is cookies need to be enabled, but most people have cookies enabled. Cookies is the default behaviour for ASP.NET. Be sure to never send cookie with secret in it over an insecure connection.Session Timeouts
In the case of a sliding forms timeout it is nice in that it can be extended forever by hitting the url and thus give a large window were someone can use a hijacked session.This is great for valid users and hackers love it too. So, turn off sliding timeout if you can to increase security.The alternate is to set a fixed session timeout, but the problem is users will lose their session at the end of the timeout no matter what they are doing. There is no perfect solution for all cases. Set according to your needs to strike a balance between security and convenience for users. Do change default values to meet specific needs.
Indirect Reference Map
Access Control
Cross Site Request Forgery
Trace.axd
Encrypt Connection String in web.config
Enable Retail Mode
Password Rules
Storage of Passwords
If a hacker can get the username and salt and the hashed value and the operation used by the system to do the hashing then they can brute force attach and recover over 65% of the passwords (on average). To do this they simply call the hashing operation with a password from their list of likely passwords using the salt that they gained access to. Now they compare the hashes. If they are the same then they know the password that was originally used by the user. They now have everything needed to login as that user.Membership Provider Default Implementation use near useless because we have both the hash and salt. Also SHA1 is too fast of an algorithm which means it can be cracked faster.
Be careful if someone has used your password on the internet and that hash has been compromised then a simple google search for that hash can show what the original password was. If a long salt was used then rainbow tables become useless. Salts make it harder to crash a hash, but it is just a matter of time and with Modern GPUs computing 7.5 billion hashes per second (in 2012) it is literally just a matter of time.
Check out Kerckhoffs' principle if you are wondering if your security is good. Basically it says, if you are not willing to give the design of how your security works and are thus relying on this lack of knowledge as part of the security then your security is not good enough. You must assume the attacker will learn how the security works soon enough.
Cryptography-Hashing
Faster algorithms are not good ironically. We actually want the hashing algorithm to take as long as we can stand. This is balanced with the processing required to login or register for example and how long it will take to hack. SHA1 is probably not sufficient anymore. One way around this is to apply the algorithm say 1000 times, but again that probably isn't enough. BCrypt allows us to directly control how many times we apply the algorithm.No algorithm is fool proof especially when lists of password and hashes and salts are cataloged. It is all about making it too difficult / time consuming / financially unjustified, etc to do it. Even the most complex algorithms can be circumvented by cataloging the input and outputs.
Cyptography- Encryption
Password Hacking tools
hashcat - advanced password recovery - brute force for comparing hashes and common hashing algorithmsRainbowCrack - Use rainbow tables to get a pregenerated list of hashes meeting different rules for password.
Restricting Urls in MVC
Don't use web.config location tag permission restrictions because it is based on url, not page. In MVC more than one route can point to the same page, but only the urls used to access them is protected in the location tag in web.config. This means if you have two routes you have to have to location tags in the web.config. This could lead to very buggy and inconsistent access. It worked well in Web Forms because the page is the url.For MVC you want to protect the Controller and actions of the controller. The way to do that is the Authorize attribute. Just using it requires authenticated users. If you want to restrict to a role you can comma separate list them as a parameter to the Authorize attribute.
Don't forget to protect resources like JavaScript, reports, ajax calls, reports, API's, pdfs, etc. Really anything that is not in the browsers url bar, but does show up in the network traffic.
Side note: Never send sensitive data in the url because they can be in web server logs, error logs, history, etc.
Just because a url can't be guessed doesn't make it secure. Urls get leaked through many different routes such that they don't have to be guessed.
Insufficient Transport Layer Protection
HSTS can be implemented in an ASP.NET MVC application by adding the following to your web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Strict-Transport-Security" value="max-age=31536000"/>
</customHeaders>
</httpProtocol>
</system.webServer>
Unvalidated Redirects and Forwards = bad reputation
Security Related Sites
nakedsecurityhak5
Troy Hunt
Friday, March 11, 2016
Search and Replace in a MS Word document
For complex stuff maybe a different choice would make sense. However, my requirements are simple much like a mail merge:
- Taking an existing MS Word file (DOCX format) as input. (Use it as a template)
- Search the MS Word file for some placeholders / tags and replace with real data, but don't save any changes to the original file since it is my template.
- Be able to write changes to a new file or stream file to browser for download
// Sample command line application
static void Main(string[] args)
{
string filename = "Test.docx";
var oldNewValues = new Dictionary<string, string>();
oldNewValues.Add("pear", "banana");
oldNewValues.Add("love", "like");
byte[] returnedBytes = SearchAndReplace(filename, oldNewValues);
File.WriteAllBytes("Changed" + filename, returnedBytes);
}
// Does a search and replace in the content (body) of a MS Word DOCX file using only the DocumentFormat.OpenXml.Packaging namespace.
// Reference: http://justgeeks.blogspot.co.uk/2016/03/how-to-do-search-and-replace-in.html
public static byte[] SearchAndReplace(string filename, Dictionary<string, string> oldNewValues)
{
// make a copy of the Word document and put it in memory.
// The code below operates on this in memory copy, not the file itself.
// When the OpenXml SDK Auto saves the changes (that is why we don't call save explicitly)
// the in memory copy is updated, not the original file.
byte[] byteArray = File.ReadAllBytes(filename);
using (MemoryStream copyOfWordFile = new MemoryStream())
{
copyOfWordFile.Write(byteArray, 0, (int)byteArray.Length);
// Open the Word document for editing
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(copyOfWordFile, true))
{
// Get the Main Document Part. It is really just XML.
// NOTE: There are other parts in the Word document that we are not changing
string bodyAsXml = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
bodyAsXml = sr.ReadToEnd();
}
foreach (var keyValue in oldNewValues)
{
string oldValueRegex = keyValue.Key;
string newValue = keyValue.Value;
// Do the search and replace. Here we are implementing the logic using REGEX replace.
Regex regexText = new Regex(oldValueRegex);
bodyAsXml = regexText.Replace(bodyAsXml, newValue);
}
// After making the changes to the string we need to write the updated XML string back to
// the Word doc (remember it is in memory, not the original file itself)
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(bodyAsXml);
}
}
// Convert the in memory stream to a byte array (binary data)
// NOTE: These bytes can be written to a physical file or streamed back to the browser for download, etc.
byte[] bytesOfEntireWordFile = copyOfWordFile.ToArray();
return bytesOfEntireWordFile;
}
}
After calling the SearchAndReplace method you have the bytes that make up the MS Word file. It is up to you what you want to do with it. You can save it a file or stream it to the browser when a user clicks a link to download a file.
To write the file to another file (leaving the original unchanged), use the following line:
File.WriteAllBytes(newFilename, returnedBytes);
To stream the bytes back to a browser via a Action method in a ASP.NET MVC controller, use the following:
return File(returnedBytes, "application/msword", "Filename to download as here.docx");
NOTE: Original code inspired by this MSDN example and additional a post or other page I can't remember (sorry).
Thursday, December 3, 2015
Passing additional view data to a Edit to make sharing a EditorTemplate on an Edit and Create view.
Imagine you have a Editor in Shared\EditorTemplates\Person.cs for an object (Person in this example) and two views for an Order entity that is showing edit fields for Order obeject and the Person object. The two EditorTemplates are Person\Edit.cshtml and Person\Create.cshtml. To use the Person EditorTemplate in the Order Edit AND Create view we need to make sure we always pass a value for the Person.OrderID. If we don't do this, the problem is that when we use the editor in the context of the Order\Create.cshtml View the Model is null and validation for the hidden field will have a value of null. When it is on Order\Edit.cshtml the model will not be null and we will have a value for model (a Person object) and thus have the value Model.OrderID. It is really the Create that requires this work around, but we want to be able to use the EditorTemplate even when it is on a Create view. Below is the code needed
Code located in the Order\Edit.cshtml View
model in this context is the Order object
NOTE: We ARE passing MyOrderID value here since we do need the editor to know and keep the value.
@Html.EditorFor(model => model.Person, new { MyOrderID = Model.OrderID })
NOTE: When we set MyOrderID, it is scoped to the EditorTemplate that we are passing the value to. However, if we put the value in the ViewBag or ViewData directly (at the top or Order\Edit.cshtml for example) then it is available to all Views and EditorTemplates in this context.
Code located in the Order\Create.cshtml View
model in this context is the Order object
NOTE: we are not passing the MyOrderID value here since we just need any value (-1 was arbitrarily chosen to be safe) and will be assigned by the Entity Framework when it is saved to the database. Most importantly it will pass the validation and the model will be valid until then.
@Html.EditorFor(model => model.Person)
Code in the partial view ( in EditorTemplates folder makes it a template) for the Person object.
model in this context is the Person object
NOTE: If no value is passed using ViewBag.MyOrderID then we use -1, otherwise we use the passed value (usually from the Order\Edit.cshtml View)
@Html.HiddenFor(model => model.OrderID, new { Value = ViewBag.MyOrderID ?? -1 })
You can also use a strongly-typed ViewModel and pass all data to it instead of using the ViewBag.
Wednesday, December 2, 2015
Configure Code First migrations to use Singular Table Names
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// make the table names singular instead of plural
modelBuilder.Conventions.Remove
base.OnModelCreating(modelBuilder);
}
}
Thursday, November 26, 2015
Resetting migrations when using Code First Migrations in MVC
- Delete all the migrations folder in your project except Configuration.cs
- Move Configuration.cs to some place safe and remove from the migrations folder
- Delete the records in the __MigrationHistory table in your database
- Then run the following command in the Package Manager Console:
>Enable-Migrations -EnableAutomaticMigrations -Force
NOTE: This will recreate your Configuration.cs - Replace the new Configuration.cs with the Configuration.cs that we moved to a safe place earlier
- Then run the following command in the Package Manager Console:
>Add-Migration Reset
NOTE: The name is not important - This will create a file in the migrations folder.
- Open the new migration file and comment out all the code in the Up() method such that the body of the method is just commented out code.
- Save and Build the project
- Then run the following command in the Package Manager Console:
>Update-Database - Uncomment the Up() method.
- Save and Build the project.
Good Articles on MVC and .NET
Getting Started
Implementing Basic CRUD Functionality with the Entity Framework in ASP.NET MVC Application - Good step by step tutorial for MVC 5 (not MVC 6). It also shows how to use TryUpdateModel to specify what can be bound to each object. This is a bit cleaner and more object specific, but does require a bit of code.Binding
ASP.NET MVC - The Features and Foibles of ASP.NET MVC Model Binding - a great post that gives an in-depth explanation of how the binder works and how it can be extended.Prefixing Input Elements Of Partial Views With ASP.NET MVC - Explains how to make a partial view generate html with references that the Binder can understand properly. Also shows a generic method for passing the prefix to the Partial View. It doesn't say it, but creating Edit Templates and EditorFor() instead of Partial Views will also solve this problem.
Model Binding To A List - Explains how to set the Name html form property so that the binder will create the collection.
Mass Assignment / Over-posting
6 Ways To Avoid Mass Assignment in ASP.NET MVC - If you use the Include or Exclude parameters with the Bind attribute it doesn't seem so say it anywhere, but the names of the fields are the same as what show up in Request.Form. So, things like Person.Address.Name, Person.Address.ID, and Person.Address would all need to be added to the Include parameter in order for fields bound to related objects to be allowed through the Include() list and be added to the Request.Form colletion.Sharing Create / Edit Screens
ASP.NET MVC - using the same form to both create and edit - forum on how this could be implementedView Model
How to Use ViewModel with ASP.NET MVC - shows how to implement the repository pattern, how to organize your project, and how to use a View Model.Videos
Building Applications in ASP.NET MVC 4 - very in depth video on how to build MVC applications. Most of it still applies to MVC 6. It has details on certain topics that are not covered in the MVC 5 version of the video.Building Applications in ASP.NET MVC 5 - very good video and in depth video on how to build MVC applications.
Best Practices
Best Practices for ASP.NET MVC - this is a bit old, from 2010, but still has some good advise.Dependency Injection
Dependency Injection and Unit Of Work using Castle Windsor and NHibernate - good example of how to use DI and UOW in MVC application. It shows NHibernate, but it can be used for Entity Framework. It also shows how to use in the context of the different layers of an application.Castle Windsor Tutorial 1 - I highly recommend reviewing this tutorial. It shows how to create a Castle Windsor container application. It is complex enough to see how a whole application can be done with only calling the container 3 times. It also found it useful to modify the code such that it does NOT use IoC (i.e. not using Castle Windsor). This involves instantiating objects by hand. Then a line at a time, I removed the code I added to hardcode the creation of an object and added the appropriate line in the Installer for that object. Run the application between changes to see how the container actually instantiates the objects automatically once they are registered (in the installer).
Castle Windsor Tutorial 2 - In the case where you do need to create your own instances of an object and still use IoC, you should use TypedFactoryFacility.
Krzysztof Koźmic on software - talks about IoC concepts in depth.
What's New
Top 10 Changes in ASP.NET 5 and MVC 6Entity Framework
Configuring Relationships with the Fluent API i.e. configuring Cascade delete and one-to-one relationships.Unit Testing
Testing Entity Framework with a MOQ - step by step instructions on how to test the EF6+ using MOQ. I am using the latest EF6 and did NOT have to change the class the inherits from DbContext such that the DbSets are virtual because they are already that way in the T4 templates.Also, if you need to access the .SetAttributes for MSTesting - includes samples of attributes for setup and cleanup methods that apply to tests, classes, assemblies, etc depending on the scope you need. A class can be created that has assembly specific setup and cleanup and doesn't need to have any tests actually in the class itself. Teh class does need to be marked as TestClass() though.
Unit Testing Good Patterns #3 - Know Your Moq Argument Matchers - this is an excellent read to understand how to use the It and Verify classes.
Keeping up
Code MagazineEntity Framework Team Blog
Wednesday, November 25, 2015
Using CDN (Content Delivery Networks) with ASP.NET MVC
- Files are downloaded from the best geographical location
- CDN networks are trusted and built for high availability and high usage
- The browser can download files from several servers at the same time.
- CDN networks can use caching to further improve performance
In BundleConfig.cs you can specify a CDN (Content Delivery Networks) url and a fallback url (on web app) if the CDN fails for some reason. The failure is determined on the browser side by checking a javascript expression specified by CdnFallbackExpression.
Here is an example of what can be done for the ~/bundles/query that is set by default on a new project.
// use CDN if it is available.
// NOTE: Won't show on local machine unless turn debugging off in web.config
bundles.UseCdn = true;
var bundle = new ScriptBundle("~/bundles/jquery",
@"//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js");
bundle.CdnFallbackExpression = "window.jquery";
bundle.Include("~/Scripts/jquery-{version}.js");
bundles.Add(bundle);
Be sure to set the bundles.UseCdn = true. Also, if you are running your project under debug (set in the web.config) then you won't get the bunding, minimizing, optimizations, etc, but you would in production. To force these in development, set debugging to false in the web.config.
Here is a list of CdnFallbackExpression values for common CDNs.
## Library ## ## Expression ##
jQuery window.jQuery
jQuery.UI window.jQuery.ui
Modernizr window.Modernizr
Bootstrap $.fn.modal
jquery.transit $.transit
jquery.validate $.validator
json2 JSON.stringify
webfont WebFont
jquery.blockUI $.unblockUI()
respond window.respond
moment window.moment
dataTables$.fn.dataTable
NOTE: List copied from here and the augmented.
Great post on CDN
How to change the default Name of a TextBox when using MVC, Razor
Here is the simple example using @Html.TextBoxFor() to change it from the default of "StartTime" to "MyStartTime":
@Html.TextBoxFor(modelItem => item.StartTime, new { Name = "MyStartTime"})
Below is an example of how to set the Name of the StartTime TextBox when looping through a collection of complex objects such as an Appointment
In the html, the INPUT will have a names like:
Appointments[0].StartTime
Appointments[1].StartTime
The example below formats the Name html property to the format that the MVC binder understands and will automatically create the Appointment objects and bind to them.To better understand how the binding in MVC works, check out this article.
This is possible because @Html.EditorFor takes a parameter for the Name, but @Html.HiddenFor.
If you want to use @Html.TextBoxFor instead, it doesn't have this option, but we can use the htmlAttributes parameter. In this case, Name is CASE SENSITIVE. Using name will not work right.
@{
var @i = 0;
}
@foreach (var item in Model)
{
@Html.EditorFor(modelItem => item.StartTime, "TextBox", "Appointments[" + @i + "].StartTime", null)
@Html.TextBoxFor(modelItem => item.StartTime, new { Name = "Appointments[" + @i + "].StartTime"})
i++;
}
NOTE: You can also use a for loop instead of the foreach.
NOTE: This technique should also work for the other Html helpers, but I have not tested it.
Monday, November 23, 2015
Get a list of ApplicationUsers (Users) in MVC 6
The following will work from any controller.
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
...
var users = Request.GetOwinContext().GetUserManager
The generated controllers have a line like this:
private ApplicationDbContext db = new ApplicationDbContext();
After the above initialization takes place, you can also get a list of users by simply doing:
db.Users
Notice, I am NOT using db.ApplicationUsers which you may have been tempted to add to the ApplicationDbContext class using the following:
public DbSet
The problem as noted here is that that IdentityDbContext already has the following defined.
public virtual IDbSet
So, by adding the ApplicationUsers line above you have added two properties that map to the ApplicationUsers. Here is the error you will get if you have done this:
Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'MyApp.Models.ApplicationUser'.
Thursday, January 10, 2013
Introduction to Razor in MVC
Razor is a view engine that is used in MVC 3 and later. Files use the file extension .cshtml.
One of the nice things is that it is unit testable with standard Visual Studio unit tests.
A cleaner and more elegant view engine than the default view engine.
You can use multiple view engines in the same project, including ones that third-parties have created.
Syntax
It is simpler to use than the Web forms engine syntax used by the default MVC view engine.
Default way: <%: Html.ActionLink(“Register”, “Register”) %>
Razor way: @Html.ActionLink(“Register”, “Register”)
You’ll notice there is no closing code block needed and the opening code block is just the @ sign which is easier to type. It will still automatically encode the string as well.
Code Block
if you are using Html.BeginForm or other blocks of code you can do something like this. No need for the old <% %> tags
@Html.BeginForm() {
… <some html here>…
}
Comments
You can do a server side comment with
@”
Comment here
”@
Layouts
Razor uses Layouts instead of Master Pages. They are just like other Razor files except it uses @RenderBody() to designate where content should be. Each view has a Layout property that you can set to the layout file. Alternatively, you can define the default by creating a file that is has a special name_ViewStart.cshtml. That way you don’t need to specify the layout property on each view. You can also put the file in subfolders in the View folder to have only the views in that subfolder be affected.
Friday, December 21, 2012
MVC and Routing Basics
Routing is located in the System.Web.Routing namespace
Can be used in MVC and also ASP.NET web forms apps.
Routing is used to map incoming URLS to action methods in a controller and optionally pass arguments to the action methods.
Generates outgoing urls (links in pages; generally used for navigation).
check out www.useit.com for guidelines on url best practices.
Routing is similar to URL Rewriting (been around for a long time in ASP.NET web forms). URL rewriting is geared towards pages and doesn’t really apply to MVC. Now you should almost always use Routing, but in MVC it is hard not to use routing.
Defining a route
- URL Pattern
- Default values
- Constraints
- Arbitrary properties
Look in the Global.asax.cs file under the RegisterRoute() method. In the RegisterRoute method you will use the MapRoute() method to specify any of the 4 items listed above. There are many overloads for this method.
routes.MapRoute(
“Default”, // route name
”{controller}/{action}/{id}”, // url pattern
new { controller = "Home”, action = “Index”, id = “”} // parameter defaults
);
The order or the MapRoute method is very important. They are processed from top to bottom. so put routes from more specific to more general.
URL Pattern
Default URL pattern: {controller}/{action}/{id}
Consists of segments. Each segment has URL parameters or placeholders and are shown as {…} and some static text.
The RouteValueDictionary holds the values that the parameters take based on the current url. For example if the url is http://localhost/Dog/Edit/3 then when the route is matched the RouteValueDictionary will contain keys and values as shown below.
controller = Dog
action = Edit
id = 3
You don’t have to use / to separate the placeholders. You can use just about anything, but it should be something that is not the data
Some other examples of url patterns:
“Brent/{controller}-{action}-{id}” –> Brent/Dog-Edit-3
“Brent/{controller}-{action}/{id}” –> Brent/Dog-Edit/3
Default Values
Works much like optional parameters in methods. If the parameter is not specified routing looks to see if there is a default value for that parameter (placeholder). They are passed to the routes.MapRoute() method.
http://localhost - default values for controller and action
http://localhost/Dog/List - default values for id
Constraint
What will happen if your url is http://localhost/Dog/Edit/3? In this example, let’s assume that the id is an int and 3 will be assigned to it. This matches the routing pattern fine, but what would http://localhost/Dog/Edit/Jewel do? It would try to assign Jewel to an int and that would not work and would result in the YSOD. To make it so the pattern is not matched we can introduce a constraint to only match numbers. Constraints can use regular expressions to control accepted values.
We could change the route to something like this using an overloaded Map method.
routes.MapRoute(
“Default”, // route name
”{controller}/{action}/{id}”, // url pattern
new { controller = "Home”, action = “Index”} // parameter defaults – notice no id default
new { id = @”\d{1,6} }
);
“Default”, // route name
”{controller}/{action}”, // url pattern
new { controller = "Home”, action = “Index”} // parameter defaults,
);
The first route is to accomplish what we were looking for. Unfortunately, it doesn’t allow for things like http://localhost and http://localhost/Dog/List. So, we had to add the second route to allow those routes.
Handling an Arbitrary Number of Parameters
Can use a catch-all parameter that:
- match URLS with arbitrary number of parameters
- Ignores slashes
- Captures everything after what matches the url pattern to the end of the url
- Excludes the query string parameters (doesn’t capture)
- MUST be the last parameter in the url
- Can only have one in url pattern
To do this, just a * to the beginning of the parameter name.
routes.MapRoute(“CatchAll”, // route name
”Catch/All/Params/{*randomParams}”, // url pattern
new { controller = "Dog”, action = “CatchAll” } // parameter defaults
);
There needs to be a method in the Dog controller called CatchAll. It would look something like this
public ActionResult CatchAll(string randomParams) {… }
A matching url might look like this: http://localhost/Catch/All/Params/and/more/stuff/goes/here.
In this example, “and/more/stuff/goes/here” would be passed to the CatchAll method.
It is up to you to do something with the string. In most cases you will parse it and do something interesting with the values in the url.
Blocking Routes
You may want to block users from particular urls. To do that you would typically put a new route as shown below as one of the first routes in your routes collection so that it matches first.
routes.IgnoreRoute(“{resource.axd/{*pathInfo}”)
or
routes.Add(new Route(“{resource}.axd/{*pathInfo}”, new StopRouteHandler()));
Both of these do the same thing.
Generating URLS
You could hardcode urls in your MVC application, but is difficult to maintain and messy. Luckily MVC makes it easy when you use the routes to automatically generate urls. To access this automatic generation you would typically use HtmlHelper.ActionLink and HtmlHelper.RouteLink helper methods.
ActionLink – the url is based on the combination of the controller and action name, and any other parameters
RouteLink – relies on the route definitions and parameters
Works just like incoming routes regard order, so Routing will match the first one it finds which is based on the order you add it to the collection of routes.
Named Routes
If you want to force a particular route to be used. This works because the route name is basically a key into the list of routes in the route collection. This affects both the automatically generated urls (see ActionLink and RouteLink) and incoming urls. This would be useful if you want to use a route that is farther down the list of routes and thus would not usually be matched. Some people say that you should not use named routes, but the choice is yours.
Monday, December 10, 2012
Intro to MVC
URLS have the default format: /domain/controller/method/ID
Controller
They are generally light, or that should be the goal. (I need to verify this comment)
Class must end in Controller suffix and implement IController interface. However, we usually inherit from the Controller class since it inherits from IController and provides more common code we need. It cannot be abstract and cannot use generic parameters.
index() is the name of the Action Method for the default method that will be called.
Unless a method says otherwise, it looks in the Views folder. It then looks for a folder named the same as the class (minus the suffix Controller). Then it looks for the page with the name that matches the method name.
Action Methods can be overloaded, but also have attributes that determine how it is used.
Requirements to be an Action method:
- Public (and not static)
- Must be defined on System.Object or Controller
- Cannot be a special method
- Cannot have a NonAction attribute.
Security Warning: Anybody on the internet can invoke any public Method in your controller unless decorated as NonAction. However, you would usually only include methods that should be invoked based on a url.
Use the [ActionName("MyNewActionNameHere")] attribute on the Action method to change how it is used in the url. This changes what is matched for routing the request.
HttpGet, HttpPost, HttpPut, HttpDelete attributes to affect what overloaded method is called based on how it is being called. The verb is based on the verb in the current request.
use HandleUnknownAction() method to change what happens when a bad url is passed (i.e. 404 error). We could redirect to error page for example.
Controllers should be simple. Logic should be in the model. A controller's job is to translate user's actions to the model, then provide a response.
It is not uncommon to directly reference the Model (including the Entity Framework) here using Linq. If you do, it is best to instantiate the Entity Framework model in the action method rather than creating it at the controller level.
Action Filters
Implemented as attributes that can be used on Action Methods in the controller or the controller itself. Can use more than one, and specify order.
AsyncTimeout, NoAsyncTimeout, Authorize, ChildActionOnly, HandleError, OutputCache, RequiresHttps, ValidateAntiforgeryToken, ValidateInput
View
use Html.RenderPartial() to render a user control
<%: ... %> will automatically html encode (if not already) what is being rendered. This is a better choice than <% ... %>
Should be as simple as possible. No calculations, etc. Logic and calculations should be in the Model.
Give the View the raw data, let it format it the way the user should see it.
Can use open source view engines such as: Spark, Nvelocity, Brail, Nhaml
Generally will want to put files, etc in the Content directory.
Use ContentResult object as a return type in the Action to send a file to the browser.
Use ViewData object for use with strongly-typed model and Dictionary (name/value pairs). Allows code nuggets (<% %>)
Code Nuggets: <% %>
<%= %> not recommended anymore, use <%: %> due to data not being encoded.
<%: %> always use instead of = nuggest since it will do same thing, but safely encode content.
HTML Helper Methods help with writing tedious common html. They are really just shortcuts to generate HTML. Examples: Html.Label(), Html.LabelFor(), Html.TextBox(), Html.TextBoxFor(), Html.BeginForm(), Html.ValidationSummary(), Html.ValidateMessageFor(), Html.ActionLink(), Html.RenderPartial(), Html.TextArea(), Html.Hidden(), Html.RouteLink(), Html.Action()
Partial Views (implemented as user Controls). They allow you to reuse html and view code. They can be handy for Create and Edit views that share nearly all the html. Generally they should be in the Views/Shared if they will be used by multiple controllers. If they will be used by one controller, but multiple views then put it in the Views/<Controller Folder>. use the Html.RenderPartial() to include the partial view on the part of the page you want it to display. Shares data with parent model by default, but this can be changed to use a different model by passing different model via Html.RenderPartial(). Partial views can be nested.
Use RenderAction() to call controller action methods from a view and display the result of that action method. useful to show data that is not part of the model of the view. Similar to using a RenderPartial(), but instead of inserting a partial view, you can insert virtually anything because most anything you return from an Action method. Beware of using this too often because the calls between controller and views becomes difficult to maintain. Only use it when needed.
HtmlHelper - AntiForgeryToken(), Encode(), EnableClientValidation(), AttributeEncode(), HttpMethodOverride(). 3 classes of helpers: 1. Untyped or regular helper methods, 2. Strongly typed helper methods, 3. templated helper methods. Lots of overloads. Searches for fields in the following order: ModelState, ViewData, and view model. Can put @ before a custom attribute that is passed to a helper. You can also use a Dictionary.
The Html.Label() helper method will use the Display() attribute from the Model to determine what text to display.
There are some high level helpers for Grids and Charts. For those, check out, WebGrid() with getHtml() and Chart with AddTitle(), AddSeries(). These are used with Razor.
Can supply a default value via an extra parameter on helper methods.
Most common Templated Helper Methods
- Display, DisplayFor, DisplayForModel
- Edit, EditorFor, EditorForModel
Models
Most any kind of technology or conventions can be used here. This would include things like Entity Framework, etc.
Encapsulates data and business rules, logic, validation, calculations, etc. This is where all the heavy lifting is done.
Use directly in conrollers and views
It is NOT required to add the suffix Model to the classes, but it does generally make it easier to follow in code.