C# MVC 4.5 dev experience

1. Say you have different environments for running project of different configurations, how to make it easy to debug and deploy in Visual Studio?

For set different configurations, use Web.config Transformation.

For direct publishing to remote server, use Web Deploy, need admin access.

We just like automation!

2. ASP.NET Identity

Authorization and authentication is a headache for web project. When creating a web MVC empty project, choose individual account for access control, and you can solve this kind of problem easily.

3. Image not found in CSS for project release mode

When deploying the VS project in release mode, it will automatically use the combined minified CSS/JS, which using a virtual directory for resource allocating. Image path in CSS may not found due to this problem, change the image URL to ‘/Content/whatevertotheimagepath’ directory.

4. How RememberMe works?

Remember Me?
If uncheck rememberme, MVC will create a default session cookie, which is usable cross tabs/pages for current login, but will be lost if user close the browser.

If check rememberme, MVC will create a persistent cookie for a default time expiration (configurable) for current login, usable cross tabs/pages, even close and re-open browser within the expiration period.

Logging for ASP.NET MVC 4: log4net

Logging is always an important part of a software project, tracing errors, passing audits, and allow monitoring etc.

I know how to use log4j in Spring framework, but today I have worked a little on C# MVC 4.

How to easily add logging into ASP.NET MVC 4 code base ?

I use log4net, and you can simply download it from VS NuGet store.

Steps for setting up after installation of log4net package:

1. Open  Global.asax.cs

protected void Application_Start() {
log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));

2. Open Startup.cs

[assembly: log4net.Config.XmlConfigurator(ConfigFile="Web.config", Watch = true)]

3. Open Web.config

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="app-log.txt" />
<appendToFile value="true"/>
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %logger (line:%line) - %message%newline" />
<level value="DEBUG"/>
<appender-ref ref="RollingFileAppender" />

4. Any namespace, say in Controller:

using log4net;
public class AccountController : Controller
readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public AccountController()
private bool try(){ log.Error("Error message"); }

The only thing missing here is that I have not tried to log Database SQL error. May update this later.

Razor Syntax Samples

Implicit Code Expression

Code expressions are evaluated and written to the response. This is typically how you display a value in a view:


Code expressions in Razor are always HTML encoded.

Explicit Code Expression

Code expressions are evaluated and written to the response. This is typically how you display a value in a view:

<span>1 + 2 = @(1 + 2)</span>

Unencoded Code Expression

In some cases, you need to explicitly render some value that should not be HTML encoded. You can use the Html.Raw method to ensure that the value is not encoded.


Code Block

Unlike code expressions, which are evaluated and outputted to the response, blocks of code are simply sections of code that are executed. They are useful for declaring variables that you might need to use later.


int x = 123;

string y = “because.”;


Combining Text and Markup

This example shows what intermixing text and markup looks like using Razor.

@foreach (var item in items) {

<span>Item @item.Name.</span>


Mixing Code and Plain Text

Razor looks for the beginning of a tag to determine when to transition from code to markup.

However, sometimes you want to output plain text immediately after a code block. For example, the following sample displays some plain text within a conditional block.

@if (showMessage) {

<text>This is plain text</text>



@if (showMessage) { @:This is plain text.


Note that two different ways exist for doing this with Razor. The first case uses the special <text> tag. The tag

itself is a special tag and is not written to the response; only its contents are written out. I personally like this approach because it makes logical sense to me. If I want to transition from code to markup, I use a tag.

Others prefer the second approach, which is a special syntax for switching from code back to plain text, though this approach works only for a single line of text at a time.

Escaping the Code Delimiter

As you saw earlier in this chapter, you can display @ by encoding it using @@. Alternatively, you always have the option to use HTML encoding:


The ASP.NET Twitter Handle is @aspnet


The ASP.NET Twitter Handle is @@aspnet

Server-Side Comment

Razor includes a nice syntax for commenting out a block of markup and code.


This is a multiline server side comment.

@if (showMessage) {



All of this is commented out.


Calling a Generic Method

Calling a generic method is really no different from calling an explicit code expression. Even so, many folks get tripped up when trying to call a generic method. The confusion comes from the fact that the code to call a generic method includes angle brackets. And as you’ve learned, angle brackets cause Razor to transition back to markup unless you wrap the whole expression in parentheses.



Layouts in Razor help maintain a consistent look and feel across multiple views in your application.

If you’re familiar with Web Forms, layouts serve the same purpose as master pages, but offer both a simpler syntax and greater flexibility.









TODO task for learning ASP.NET MVC 5:

1. Consume ArcGIS REST API service in server side, i.e. generate token service for login

2. Customize login page and redirect, aka. routing issue

3. User registration module for application with SQL Express

4. Port ePlanner 2.0 to MVC and make it run

5. Write more using C#

Finish the book Professional ASP.NET MVC 5.


1. Make Yahoo! Web Service Rest API Call using C#

2. Using Secured Web Services and Tokens

string url = tokenServiceUrl + "?request=getToken&username=
myuser&password=secret"; System.Net.WebRequest request = System.Net.WebRequest.Create(url);

string myToken, errorMsg;
try {
   System.Net.WebResponse response = request.GetResponse();
   System.IO.Stream responseStream = response.GetResponseStream();
   System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream);

   myToken = readStream.ReadToEnd();
catch (WebException we) {
   if (we.Message.Contains("403")
      errorMsg = "Server returned forbidden (403) code."

3. How to Customize ASP.NET MVC Authentication

4.ASP.NET MVC Authentication – Customizing Authentication and Authorization The Right Way

5.Sesseion Hijacking

6. Read Web.config data
in Web.config add:

<add key="customsetting1" value="Some text here"/>


			System.Configuration.Configuration rootWebConfig1 =
			if (rootWebConfig1.AppSettings.Settings.Count > 0)
				System.Configuration.KeyValueConfigurationElement customSetting = 
				if (customSetting != null)
					Console.WriteLine("customsetting1 application string = \"{0}\"", 
					Console.WriteLine("No customsetting1 application string");