Category Archives: Interview question

Q How can you prevent a cleint by using Action method in MVC?

I have two actions inside my controller (shoppingCartController)

public ActionResult Index()
{
	//some stuff here
	return View(viewModel);
}

public ActionResult AddToCart(int id)
{

	return RedirectToAction("Index");

}

Is there anyway to prevent the users from directly calling the index action by typing the url in the browser?
For example: If the user browses to shoppingCart/index be redirected to Home/Index.
Solution
You could use the [ChildActionOnly] attribute on your action method to make sure it’s not called directly, or use the ControllerContext.IsChildAction property inside your action to determine if you want to redirect.
For example:

//[ChildActionOnly]
public ActionResult Index()
{
    if(!ControllerContext.IsChildAction)
    {
       //perform redirect here
    }

    //some stuff here
    return View(viewModel);
}

Reference:
https://stackoverflow.com/questions/9407172/asp-net-mvc-how-to-prevent-browser-from-calling-an-action-method

 

Advertisements

Leave a comment

Filed under C#, Interview question, MVC, Uncategorized

Q Explain deferred execution vs. immediate execution in LINQ. Provide examples.

In LINQ, deferred execution simply means that the query is not executed at the time it is specified. Specifically, this is accomplished by assigning the query to a variable. When this is done, the query definition is stored in the variable but the query is not executed until the query variable is iterated over. For example:

DataContext productContext = new DataContext();

var productQuery = from product in productContext.Products
where product.Type == "SOAPS"
select product; // Query is NOT executed here

foreach (var product in productQuery) // Query executes HERE
{
	Console.WriteLine(product.Name);
}

You can also force immediate execution of a query. This can be useful, for example, if the database is being updated frequently, and it is important in the logic of your program to ensure that the results you’re accessing are those returned at the point in your code where the query was specified. Immediate execution is often forced using a method such as Average, Sum, Count, List, ToList, or ToArray. For example:

DataContext productContext = new DataContext();

var productCountQuery = (from product in productContext.Products
where product.Type == "SOAPS"
select product).Count(); // Query executes HERE

Ref
https://www.toptal.com/dot-net/interview-questions

Leave a comment

Filed under C#, Interview question