Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. Show all posts

Friday, 25 January 2019

pass parameters in RedirectToAction from one controller to another

in First controller action method

               var res = new ResponseModel();   // with many properties

                        //var routeValues = new RouteValueDictionary {
                        //  { "res", JsonConvert.SerializeObject(res) }
                        //};

                        //return RedirectToAction("Index", "Customer", routeValues);

In Customer controller index method

        public ActionResult Index(string res)
        {
            if (!string.IsNullOrEmpty(res))
            {
                var paymentRes = JsonConvert.DeserializeObject<ResponseModel>(res);
                if (paymentRes.IsSuccessful)
                {
                    ViewBag.paymentMessage = paymentRes.Message;
                }
                else
                {
                    ViewBag.paymentMessage = paymentRes.ErrorMessage;
                }
            }
            return View();
        }
                    

Monday, 30 January 2017

Can you remove default View Engine in ASP.NET MVC? How?

We can customize view engines in ASP.NET MVC application.

If you are not using any view engine like ASPX View Engine, better you remove it to improve the performance, it is one of the MVC performance tuning tips from the bunch.

Removing the Web Form view engine is easy in MVC. We can remove all the view engines and add only Razor view engine by using Application_Start event of Global.asax.cs file like below.

  1. protected void Application_Start()
  2. {
  3. //Remove All Engine
  4. ViewEngines.Engines.Clear();
  5. //Add Razor Engine
  6. ViewEngines.Engines.Add(new RazorViewEngine());
  7. ...
  8. }

NOTE:
  1. After removing Web Form engine, Razor View Engine will be almost twice as fast with the Web Form engine.
  2. Use this when you are sure that you will use only Razor views. It will be helpful to you.
  3. If you are using both type of views (ASPX & Razor), don't implement this.
You can also customize the view engines. for more click 

Tuesday, 27 December 2016

Different methods used to render the views and Partial views in ASP.Net MVC


1. RenderPartial  - RenderPartial method is useful when the displaying data in the partial view is already in the corresponding view model.
@{Html.RenderPartial("_partialView");}
This method returns void. And simple to use and no need to create any action.
This method is faster than Partial method since its result is directly written to the response stream which makes it fast.

2. Partial - Like RenderPartial method, Partial method is also useful when the displaying data in the partial view is already in the corresponding view model.
@Html.Partial("_partialView")
Simple to use and no need to create any action.This method result can be stored in a variable, since it returns string type value.
Renders the partial view as an HTML-encoded string.

3. RenderAction - RenderAction method is useful when the displaying data in the partial view is independent from corresponding view model.
@{Html.RenderAction("Action_Name","Controller-Name");}
For this method, we need to create a child action for the rendering the partial view.
This method is the best choice when you want to cache a partial view.
This method is faster than Action method since its result is directly written to the HTTP response stream which makes it fast.

4. Action - Action method is useful when the displaying data in the partial view is independent from corresponding view model.
@Html.Action("Action_Name","Controller-Name");
For this method, we need to create a child action for the rendering the partial view.This method result can be stored in a variable, since it returns string type value.
Renders the partial view as an HtmlString .

This method is also the best choice when you want to cache a partial view.

5. Direct return from Controller 


public ActionResult Action()
        {
            return PartialView("PartialViewName");
OR
            return View("ViewName");

        }

For More check Views Partial Views

Saturday, 24 December 2016

What is Caching? Explain Output Cache.

Caching is a most important aspect of high-performance web application. Caching provides a way of storing frequently accessed data and reusing that data. Practically, this is an effective way for improving web application’s performance.
Output Cache can dramatically improve the performance of an ASP.NET MVC application. The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked.
The OutputCache filter allow you to cache the data that is output of an action method. By default, this attribute filter cache the data till 60 seconds. After 60 sec, if a call was made to this action then ASP.NET MVC will cache the output again.
Enabling Output Caching
You enable output caching by adding an [OutputCache] attribute to either an individual controller action or an entire controller class as below.
[OutputCache(Duration=10, VaryByParam="none")]
        public ActionResult Index()
        {
            return View();
        }
Output Caching Location
By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. You can control the content's cached location by changing the location parameter of the OutputCache attribute to any of the following values: 
  • Any (Default): Content is cached in three locations: the web server, any proxy servers, and the web browser.
  • Client: Content is cached on the web browser.
  • Server: Content is cached on the web server.
  • ServerAndClient: Content is cached on the web server and and the web browser.
  • None: Content is not cached anywhere.
[OutputCache(Duration=3600, VaryByParam="none", Location=OutputCacheLocation.Client, NoStore=true)]
        public string GetName()
        {
            return "Hi " + User.Identity.Name;
        }
Varying the Output Cache
In some situations, you might want different cached versions of the very same content, So for that we use "VaryByParam" as in above code.
In case we have multiple action methods across controllers needing the same caching behavior, we can put this caching values in the web.config and create a cacheprofile for it.
<caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="MyCacheProfile"
               duration="30"
               varyByParam="id"
               location="Any" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
And to use these values in the action methods we just need to specify the CacheProfile name in the action method.
[OutputCache(CacheProfile = "MyCacheProfile")]
public ActionResult Dummy()
{  
    return View();
}
For more Cache MSDN Cache

Monday, 19 December 2016

Different techniques to handle Exceptions in ASP.NET MVC


There are many ways to handle exceptions. We will discuss here some of them.

1. Try - Catch Block


public ActionResult SomeError()
{
try
{}
catch(Exception ex)
{return View("Error");}
}

2. By Overriding 'OnException' method.

In this we override the 'OnException' method of controller and specify error page.
public class HomeController : Controller
 {
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;

     var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");

     filterContext.Result = new ViewResult()
{
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
     };

        }
}
and in view we have to use
@Model.Exception;

but this way does not provide code re-usability across multiple controllers.

3. HandleError Attribute

1. we put this attribute on action in controller as below.
public class HomeController : Controller
 {
        [HandleError()]
        public ActionResult SomeError()
        {
            throw new Exception("test");
        }
}
2. Add custom error code in web config.
<system.web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.web> 

If you want different views for different exception types then modify 'HandleError' attribute as below.
public class HomeController : Controller
{
[HandleError(ExceptionType=typeof(ArithmeticException),View="Arthimetic")]
[HandleError(ExceptionType = typeof(NotImplementedException),View ="Error1")]
public ActionResult SomeError()
{
    
}
}

4. Create separate class Inheriting from 'ErrorHandleAttribute'.

In this way we can use code re-usability concept across all controller. we create separate class that inherit from 'ErrorHandleAttribute' class and then we use this 'Errorclass' as an Attribute for Actions in controllers.
public class ErrorClass : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error1",
                ViewData = new ViewDataDictionary(model)
            };
        }
    }

5. Handling Http Errors

There are many error like 'FileNotFound', Http 500 error etc . for these we use customer error in web config.
<system.web>
<customErrors
                  mode="On" defaultRedirect="Error1">
<error statusCode="404" redirect="~/Testing/NoPageFound"/>
</customErrors>
</system.web> 

6. Global Error handling 
We write code in Global.asax file in Application_Error event.
protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Server.ClearError();
            Response.Redirect("/Home/Error");
        }


Sunday, 11 December 2016

Points to be remember for Deploying ASP.Net MVC Application in Production

1. To make application Offline use App_Offline.htm


If you are running your application within a .NET 4.0 application pool (IIS 7.0 or IIS 7.5) or your web site is configured as an ASP.NET 4.0 web site (IIS 6.0) and would like to show your clients an “under maintenance” page for a limited time, the easiest way is to put a file named app_offline.htm in your web site’s root folder. Then your application will be taking offline and the clients will be served with app_offline.htm page whatever their requests are.

2. Deploy application with debug="false"

When we develop asp.net application using Visual Studio, the default value for debug attribute is true. This setting will help developers to debug the application in development environment. For example, executing the application in this mode will not cache the resource files rendered by WebResources.axd handler. This prevents the need to clear the temporary cache every time when the developer needs to check the changes done. There will be other useful things done for developers for debugging like debug symbols, settings that will enable breakpoints etc. These setting will give a poor performance in production if released in the default debug mode (false).
So, never release your website with debug mode set to true. It should be set to false in web.config when moving to production.
<compilation debug=”false”/>
Debug mode to 'true' results following disadvantage.
  Code execution will be slow.
  Compilation will be slow since batch compilation is disabled.
  Memory consumption is higher since there are additional debug symbols, etc.
  Resources downloaded with webresources.axd will not be cached.

Alternate will be <deployment retail=”true”/> in machine.config. If you are a server administrator, make this change in machine.config so that it will enforce the debug attribute in the application’s web.config to false. It also disables the page output tracing and the ability to show the detailed exception report to the remote users when there is an exception.

3. Configure Custom Error Page in Web.Config file


In web.config use code.
<customErrors defaultRedirect="url"
              mode="On|Off|RemoteOnly">
     <error. . ./>
</customErrors>


ON - Specifies that custom errors are enabled. If no defaultRedirect attribute is specified, users see a generic error. The custom errors are shown to the remote clients and to the local host.

OFF - Specifies that custom errors are disabled. The detailed ASP.NET errors are shown to the remote clients and to the local host.

REMOTEONLY - Specifies that custom errors are shown only to the remote clients, and that ASP.NET errors are shown to the local host. This is the default value.

4. Separate Application pool For each Application

Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availability for any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected.

5. Custom Service Account for ASP.NET app pools

A custom account is useful in the following situations:
  • When you want to improve security and make it easier to trace security events to the corresponding application.
  • When you are hosting Web sites for multiple customers on a single Web server. If you use the same process account for multiple customers, source code from one customer's application may be able to access source code from another customer's application. In this case, you should also configure a custom account for the anonymous user account.
  • When an application requires rights or permissions in addition to the default permissions for an application pool. In this case, you can create an application pool and assign a custom identity to the new application pool.
  • For More Identity for an Application Pool
How to Set
  1. Open IIS Manager. For information about opening IIS Manager, see Open IIS Manager (IIS 7).
  2. In the Connections pane, expand the server node and click Application Pools.
  3. On the Application Pools page, select the application pool for which you want to specify an identity, and then click Advanced Settings in the Actions pane.
  4. For the Identity property, click the ... button to open the Application Pool Identity dialog box.
  5. If you want to use a built-in account, select the Built-in account option and select an account from the list.
  6. If you want to use a custom identity, select the Custom account option and click Set to open the Set Credentials dialog box. Then type the custom account name in the User name text box, type a password in the Password text box, retype the password in the Confirm password text box, and then click OK.
  7. Click OK to dismiss the Application Pool Identity dialog box.

6. Encrypt the Sensitive data in Web.Config file.

For more click Encrypt sensitive data

7. Deploying a Web Application Project Using a Web Deployment Package


8. For Intranet applications use Windows Authentication to connect to database


If your application is hosted in an intranet domain, then use windows authentication to connect to the database. The advantage of this approach, you can use the same windows service account configured to run your app pool in IIS 6.0 to connect to the database. This prevents the need to store the password as a clear text in web.config.

Saturday, 10 December 2016

What is CSRF attack and how can we prevent the same in MVC?

Cross-Site Request Forgery (CSRF) is an attack where a malicious site sends a request to a vulnerable site where the user is currently logged in
Here is an example of a CSRF attack:
  1. A user logs into www.example.com, using forms authentication.
  2. The server authenticates the user. The response from the server includes an authentication cookie.
  3. Without logging out, the user visits a malicious web site. This malicious site contains the following HTML form:
<h1>You Are a Winner!</h1>
  <form action="http://example.com/api/account" method="post">
    <input type="hidden" name="Transaction" value="withdraw" />
    <input type="hidden" name="Amount" value="1000000" />
  <input type="submit" value="Click Me"/>
</form>
  1. Notice that the form action posts to the vulnerable site, not to the malicious site. This is the “cross-site” part of CSRF.
  2. The user clicks the submit button. The browser includes the authentication cookie with the request.
  3. The request runs on the server with the user’s authentication context, and can do anything that an authenticated user is allowed to do.
Although this example requires the user to click the form button, the malicious page could just as easily run a script that sends an AJAX request. Moreover, using SSL does not prevent a CSRF attack, because the malicious site can send an “https://” request.
Typically, CSRF attacks are possible against web sites that use cookies for authentication, because browsers send all relevant cookies to the destination web site. However, CSRF attacks are not limited to exploiting cookies. For example, Basic and Digest authentication are also vulnerable. After a user logs in with Basic or Digest authentication. the browser automatically sends the credentials until the session ends.

Anti-Forgery Tokens

To help prevent CSRF attacks, ASP.NET MVC uses anti-forgery tokens, also called request verification tokens.
  1. The client requests an HTML page that contains a form.
  2. The server includes two tokens in the response. One token is sent as a cookie. The other is placed in a hidden form field. The tokens are generated randomly so that an adversary cannot guess the values.
  3. When the client submits the form, it must send both tokens back to the server. The client sends the cookie token as a cookie, and it sends the form token inside the form data. (A browser client automatically does this when the user submits the form.)
  4. If a request does not include both tokens, the server disallows the request.
Here is an example of an HTML form with a hidden form token:
<form action="/Home/Test" method="post">
    <input name="__RequestVerificationToken" type="hidden"   
           value="6fGBtLZmVBZ59oUad1Fr33BuPxANKY9q3Srr5y[...]" />    
    <input type="submit" value="Submit" />
</form>
Anti-forgery tokens work because the malicious page cannot read the user’s tokens, due to same-origin policies. (Same-orgin policies prevent documents hosted on two different sites from accessing each other’s content. So in the earlier example, the malicious page can send requests to example.com, but it cannot read the response.)
To prevent CSRF attacks, use anti-forgery tokens with any authentication protocol where the browser silently sends credentials after the user logs in. This includes cookie-based authentication protocols, such as forms authentication, as well as protocols such as Basic and Digest authentication.
You should require anti-forgery tokens for any nonsafe methods (POST, PUT, DELETE). Also, make sure that safe methods (GET, HEAD) do not have any side effects. Moreover, if you enable cross-domain support, such as CORS or JSONP, then even safe methods like GET are potentially vulnerable to CSRF attacks, allowing the attacker to read potentially sensitive data.

Anti-Forgery Tokens in ASP.NET MVC

To add the anti-forgery tokens to a Razor page, use the HtmlHelper.AntiForgeryToken helper method:
@using (Html.BeginForm("Manage", "Account")) {
    @Html.AntiForgeryToken()
}
This method adds the hidden form field and also sets the cookie token.

Anti-CSRF and AJAX

The form token can be a problem for AJAX requests, because an AJAX request might send JSON data, not HTML form data. One solution is to send the tokens in a custom HTTP header. The following code uses Razor syntax to generate the tokens, and then adds the tokens to an AJAX request. The tokens are generated at the server by calling AntiForgery.GetTokens.
<script>
    @functions{
        public string TokenHeaderValue()
        {
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken + ":" + formToken;                
        }
    }

    $.ajax("api/values", {
        type: "post",
        contentType: "application/json",
        data: {  }, // JSON data goes here
        dataType: "json",
        headers: {
            'RequestVerificationToken': '@TokenHeaderValue()'
        }
    });
</script>
When you process the request, extract the tokens from the request header. Then call the AntiForgery.Validate method to validate the tokens. The Validate method throws an exception if the tokens are not valid.
void ValidateRequestHeader(HttpRequestMessage request)
{
    string cookieToken = "";
    string formToken = "";

    IEnumerable<string> tokenHeaders;
    if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
    {
        string[] tokens = tokenHeaders.First().Split(':');
        if (tokens.Length == 2)
        {
            cookieToken = tokens[0].Trim();
            formToken = tokens[1].Trim();
        }
    }
    AntiForgery.Validate(cookieToken, formToken);
}
The below code illustrates how Anti-Forgery Token Cross Site Request Forgery:
Controller
[ValidateAntiForgeryToken] 
public class UserController : Controller
    {
        public ActionResult DeleteUser()
        {
            var userId = (int)Session["userId"];            
            DeleteUserFromDb(userId);//Function for deleting the user from Database
            return View();
         }
    }
View
@using (Html.BeginForm("DeleteUser", "User"))
{  
    @Html.AntiForgeryToken()
    <input type="submit" value="Delete My Account" />
}