if we look at ViewResult object returned by action method, ViewResult implements ActionResult(implements IActionResult) as
public class ViewResult : ActionResult
{
...
public override Task ExecuteResultAsync(ActionContext context);
}
ExecuteResultAsync seems to be the guy that generates responses.
But I always get told that it is Razor converts CSHTML files into C# classes, compiles them, and then creates new instances each time a view is required to generate a result. Below is the C# class that Razor creates for the Index.cshtml view
public class ASPV_Views_Home_Index_cshtml : RazorPage<string[]> {
...
public override async Task ExecuteAsync() {
WriteLiteral(#"<!DOCTYPE html><html><head> ...
}
}
so ExecuteAsync also seems to generate responses?
When ViewResult gets executed by the framework (i.e. calling ViewResult.ExecuteResultAsync
), it is responsible for 1. creating the IView that represents the correct cshtml files (view and layout) and 2. feeding this information to the IViewEngine. The view engine is the one responsible for compiling and writing the page contents to the output stream (i.e. calling IRazorPage.ExecuteAsync Method).
So, the ViewResult just loads everything it needs, and in the end, IRazorPage.ExecuteAsync is the one who truly writes to the output stream.
Related
I have a C# web api project, basically I need to log everytime a method is getting called (ie. method name, parameters passed, result, stacktrace (if error occured), etc).
Right now, I did this by adding few lines to every method and it seems bloated, is there more efficient way to achieve this?
Any help will be appreciated.
Thank you
Middleware is one approach, or you can also create a Filter that lets you perform 'before' and 'after' operations,
https://www.tutorialsteacher.com/webapi/web-api-filters
[Code from the above link]
public class LogDemoAttribute : Attribute, IActionFilter
{
public LogDemoAttribute()
{
}
public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
Trace.WriteLine(string.Format("Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
var result = await continuation();
Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
return result;
}
public bool AllowMultiple
{
get { return true; }
}
}
This does let you add to the Global Filters (in which case, you might as well use a Middleware), or add it selectively to certain endpoints, e.g
[ApiController]
public class PeopleController : ControllerBase
{
[LogDemo]
[HttpGet("demo/endpoint")]
public IActionResult GetAll()
{
}
}
This has the advantage that you might want to pass in some parameters to the attribute, that let you perform certain context specific behaviours.
If you want to add logging to non-controller code, then you can take this approach further to an Aspect Orientated / Decorator pattern.
https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/february/aspect-oriented-programming-aspect-oriented-programming-with-the-realproxy-class
I generally find logging parameters at the controller level is good enough, and something like Application Insights that generates telemetry that shows you what the request looks like is actually the useful bit of information.
When you're saying "method" I'm unsure if you mean literally every method or just whenever a controller is being hit. But middleware would probably be the way to go. The documentation on adding custom middleware is here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-3.1
And here is an example of error handling middleware, where you could place your logging: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1
I'm trying to make dynamic menu (stored in DB), that is showing on all web app pages.
Using Google I found that it is better to make menu view as a part of Master View (_Layout.cshtml). And because of that, every action method of the controller must contain data with the menu model. To avoid code duplication I found the solution to create a base controller and provide data using its constructor:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/passing-data-to-view-master-pages-cs
Also, I'm trying to use async/await possibilities and my PageService (menu) is using ToListAsync() to get data from DB. So now I have a problem, that BaseController constructor has an async method:
public class BaseController : AsyncController, IBaseController
{
private readonly IPageService _pageService;
public BaseController(IPageService pageService)
{
_pageService = pageService;
SetBaseViewModelAsync();
}
private async Task SetBaseViewModelAsync()
{
ViewData["Pages"] = await _pageService.GetAllAsync();
}
}
I know that this is BAD CODE, but I don't know how to design this situation properly. Maybe there is another better way to create the dynamic menu or another way to get data asynchronously?
Also, I found this article, but I don't know if I can apply its solutions because I don't know if I can handle controller instance creation:
http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html
Instead of deriving everything from a base controller (which can be a lot of extra work and testing) you can just create a controller called MenuController, create a method called Default and then call it from your Layout:
[ChildActionOnly]
public Default()
{
var viewModel = _pageService.GetAllAsync();
return Partial(viewModel);
}
in your layout:
#{Html.RenderAction("Default", "Menu");}
This is really the easiest and cleanest solution. The biggest PRO is that you can control the cache for the menu separate from the method calling. There are no good solution for asp.net-mvc (1-5) to run Async code in this fashion. (ActionFilters can't be async and (Render)Partials can't be async. You can still call an async method, it will just run Sync.
Render vs Non-Render Performance.
I changed functionality to call Html.RenderAction in my View, as Erik Philips suggested:
#{
Html.RenderAction("Index", "Pages");
}
and controller:
public class PagesController : AsyncController, IPagesController
{
private readonly IPagesService _pagesService;
public PagesController(IPagesService pagesService)
{
_pagesService = pagesService;
}
[HttpGet]
[Route("")]
public async Task<ActionResult> IndexAsync()
{
var viewModel = await _pagesService.GetAllAsync();
return PartialView("MenuPartial", viewModel);
}
}
But RenderAction doesn't work with async controller Actions:
Async PartialView causes "HttpServerUtility.Execute blocked..." exception
So seems like sync call is the only one possible here.
My code (asp.net 5, mvc 6, rc-1):
public class MyView: RazorView
{
// Constructor passing everything to base class
public async override Task RenderAsync(ViewContext context)
{
context.Writer.WriteLine("");
context.Writer.WriteLine("<!-- View: {0} -->", Path);
await base.RenderAsync(context);
context.Writer.WriteLine("");
context.Writer.WriteLine("<!-- View: {0} end -->", Path);
}
}
However this override changes somehow execution of overridden method, causing all errors in PartialViews to be executed after response has already started (so developer exception page cannot be executed = 502 bad gateway).
My goal is to decorate all views with comments indicating what file is it, just like angular js does.
Edit:
Code snippet above generally works (all views are decorated with comments) - problem occurs only when exception is thrown.
I'm having trouble in how to write my ASP.NET MVC application, mainly in how to use my business logic. I will provide just some example. I don't know if this is right:
public class UserController {
public ActionResult Create(User user){
UserService service = new UserService();
if(!service.UserExists(user.Email)){
if(service.InsertUser(user)){
service.SendConfirmation(user);
}
}
}
}
Or this is right
public class UserController {
public ActionResult Create(User user){
UserService service = new UserService();
service.CreateUser(user);
}
}
In this second example the method CreateUser of UserService will check if user exists, then will insert, then will send the email.
The main difference is that in the second example the controller calls only one method while in the second it calls many methods and receives answers, in both cases the logic is inside UserService.
What's correct?
The second one is the one to choose. It utilizes proper encapsulation. The controller should not do logic but communicate with the services and feed the views with the data and manage program flow.
however you should receive some response from your service.
In your example it could mean some enum value or a boolean value to determine if the creation of the user was successfull or anything...
on this you can then let the controller manage what view comes next and what data it gets...
The recommended way to make an edit page for ASP.NET MVC is to have two methods on a controller called Edit: one GET action and one POST action, both sharing the same name but overloaded differently. Validation errors are shown on the POST action if the edit fails. Then the user can share or bookmark the URL even if it's off of a POST: the URL goes to the GET version on the return.
So far, so good. But then there's the ASP.NET async pattern on controllers. You have EditAsync and EditCompleted. On the two different EditCompleted methods, how do you tell the GET apart from the POST? If you rename the POST action, you lose the nice behavior discussed earlier.
Is there a nice way to get these two patterns to work together?
Generally the XyzAsync() method provides the XyzCompleted() method some state object that tells it what unit of work is being performed, so the XyzCompleted() method can inspect this object and do the right thing. However, if you want to have a different Completed method for each verb, this is possible via the following:
[ActionName("Edit"), HttpGet]
public void EditGetAsync() { }
public ActionResult EditGetCompleted() { }
[ActionName("Edit"), HttpPost]
public void EditPostAsync() { }
public ActionResult EditPostCompleted() { }