zoukankan      html  css  js  c++  java
  • ASP。NET MVC采访问题与答案

    表的内容

    • 免责声明
    • 什么是MVC(模型视图控制器)?
    • 解释MVC应用程序的生命周期?
    • MVC是否适用于Windows和web应用程序?
    • 使用MVC的好处是什么?
    • MVC和三层架构有什么不同吗?
    • MVC的最新版本是什么?
    • MVC 2、3、4、5和6的每个版本有什么不同?
    • MVC中的HTML助手是什么?
    • “HTML”之间的区别是什么?文本框”和“HTML.TextBoxFor”?
    • MVC中的路由是什么?
    • 路线图编码写在哪里?
    • 我们可以将多个url映射到同一个动作吗?
    • 解释基于属性的路由在MVC?
    • 在代码中定义路由结构的优点是什么?
    • 如何使用超链接从一个视图导航到另一个视图?
    • 我们如何限制MVC操作只能被GET或POST调用?
    • 如何在MVC中维护会话?
    • tempdata、viewdata和viewbag之间有什么区别?
    • TempData和ViewData之间有什么区别?
    • “TempData”是否在下一个请求中保存数据?
    • 在“TempData”中使用Keep和Peek有什么用?
    • 什么是MVC中的部分视图?
    • 如何创建和使用部分视图?
    • 如何在MVC中进行验证?
    • 我们能一次显示所有的错误吗?
    • 如何在客户端启用数据注释验证?
    • MVC中的Razor是什么?
    • 既然已经有了ASPX,为什么还要剃须刀?
    • 那么剃须刀和ASPX哪个更合适呢?
    • 如何在MVC中进行身份验证和授权?
    • 如何实现MVC的Windows认证?
    • 如何在MVC中实现表单身份验证?
    • 如何在MVC中实现AJAX
    • AJAX中可以跟踪什么类型的事件?
    • ActionResult和ViewResult之间的区别是什么?
    • 在MVC中有哪些不同类型的结果?
    • MVC中的ActionFilters是什么?
    • 动作过滤器有哪些不同类型?
    • 如果我们有多个过滤器,执行的顺序是什么?
    • 我们可以使用MVC创建我们自己的自定义视图引擎吗?
    • 如何发送结果返回JSON格式在MVC
    • 之前是什么?
    • 但是WCF SOAP也做同样的事情,那么WebAPI有什么不同呢?
    • 有了WCF,你可以实现REST,那为什么是WebAPI呢?
    • 我们如何检测一个MVC控制器被POST或GET调用?
    • 什么是MVC中的绑定和缩小?
    • 捆绑是如何提高性能的?
    • 如何在MVC中实现绑定?
    • 如何在调试模式下测试绑定?
    • 解释缩小和如何实现它
    • 我们如何实现缩小?
    • 解释MVC中的区域?
    • 解释MVC中视图模型的概念?
    • 模型类将拥有什么样的逻辑视图?
    • 我们如何在一个视图中使用两个(多个)模型?
    • 解释MVC中显示模式的需要?
    • 解释MVC模型绑定器?
    • 解释一下MVC脚手架的概念?
    • 脚手架在内部使用什么连接到数据库?
    • 如何在MVC中进行异常处理?
    • 如何处理在一个MVC视图中指向多个动作的多个提交按钮?
    • 什么是CSRF攻击,如何在MVC中防止这种攻击?

    免责声明

    阅读这些MVC面试问题并不意味着你就能清楚地了解MVC面试。本文的目的是在进行MVC访谈之前快速复习一下MVC知识。这篇文章并没有一步一步地教授Asp.net MVC,它只是去MVC面试前最后一分钟的复习表。

    如果你想从头开始学习MVC,你可以从阅读学习MVC(模型视图控制器)一步一步7天开始,或者你也可以从我在YouTube上的MVC(模型视图控制器)系列视频开始。

    如果你想在短时间内学习MVC 5,也就是2天。下面16个小时的视频系列也是如此。

    Image 1

    需要帮助来改进这篇文章

    我已经尽了我最大的努力来涵盖我在MVC访谈中遇到的问题。但我觉得下面的问题是不够的,在真正的MVC访谈中,更多的是问。如果你能在下面的评论中分享你的问题。我很乐意将它们合并到本文中,这样其他人也会受益。 如果你的问题很好,而且我喜欢,我会寄给你一份免费的。net面试问题手册,只在印度(对不起,我对其他国家不那么富有)。

    什么是MVC(模型视图控制器)?

    MVC是一种分离表示和用户交互的体系结构模式。它被分为三个更广泛的部分:模型、视图和控制器。下面是他们各自处理任务的方式。

    • 视图负责外观和感觉。
    • 模型表示现实世界对象,并向视图提供数据。
    • 控制器负责获取最终用户请求并加载适当的模型和视图。

    Image 2

    图:MVC(模型视图控制器)

    解释MVC应用程序的生命周期?

    下面的图表总结了在MVC应用程序生命周期中发生的六个更广泛的事件。

    Image 3 图片来源:- http://www.dotnetinterviewquestions.in/article_expl-mvc-applicationlifecycle_210.html

    任何web应用程序都有两个主要的执行步骤:首先理解请求,然后根据请求的类型发送适当的响应。MVC应用程序的生命周期并不不同,它有两个主要阶段,首先是创建请求对象,其次是发送我们的响应到浏览器。

    创建请求对象:请求对象的创建有四个主要步骤。下面是对同一的详细解释。

    第1步填充route: - MVC请求被映射到路由表,路由表依次指定要调用的控制器和操作。因此,如果请求是第一个请求,那么首先要做的就是用routes集合填充route表。路由表的填充发生在全局路径中。asax文件。

    根据发送的URL,“UrlRoutingModule”搜索路由表来创建“RouteData”对象,该对象包含要调用的控制器和动作的详细信息。

    第3步创建请求上下文:-“RouteData”对象用于创建“RequestContext”对象。

    这个请求对象被发送到“MvcHandler”实例来创建控制器类实例。一旦控制器类对象被创建,它就会调用控制器类的“Execute”方法。

    创建响应对象:-此阶段有两个步骤执行操作,最后将响应作为结果发送给视图。

    MVC是否适用于Windows和Web应用程序?

    与Windows相比,MVC架构更适合web应用程序。对于窗口应用程序,MVP,即。,“模型视图演示器”更适用。如果你正在使用WPF和Silverlight, MVVM更适合绑定。

    使用MVC的好处是什么?

    MVC有两大好处:

    • 当我们将代码移到一个单独的类文件时,关注点分离就实现了。通过将绑定代码移动到单独的类文件中,我们可以在很大程度上重用代码。
    • 自动化UI测试是可能的,因为现在后面的代码(UI交互代码)已经转移到一个简单的。net类中。这给了我们编写单元测试和自动化手工测试的机会。

    MVC和三层架构有什么不同吗?

    MVC是三层传统架构的进化。三层架构中的许多组件都是MVC的一部分。下面就是映射的过程:

    三层/分层架构模型视图控制器架构外观和感觉用户界面视图UI逻辑用户界面控制器业务逻辑/验证中间层模型请求首先被发送到用户界面控制器数据访问层数据访问层

    Image 4

    图:三层架构

    MVC的最新版本是什么?

    MVC 6是最新的版本,也被称为ASP VNEXT。

    MVC 2、3、4、5和6的每个版本有什么不同?

    MVC 6

    ASP。NET MVC和Web API已经合并为一个。

    依赖注入是MVC的内建部分。

    并排部署应用程序的运行时和框架

    一切都打包在NuGet中,包括。net运行时本身。

    新的基于JSON的项目结构。

    不需要为每次更改重新编译。只需点击保存并刷新浏览器。

    使用新的Roslyn实时编译器完成编译。

    vNext是通过。net基金会开源的,并接受公众的捐助。

    vNext(和Rosyln)现在也可以在Mono上运行,在Mac和Linux上都可以。

    MVC 5

    一个ASP.NET

    基于属性的路由

    Asp。净的身份

    在MVC模板中引导

    身份验证过滤器

    过滤器覆盖

    MVC 4

    ASP。净Web API

    已刷新和现代化的默认项目模板

    新的移动项目模板

    支持移动应用的许多新特性

    增强了对异步方法的支持

    MVC 3

    剃须刀

    现成的项目模板

    支持HTML 5的模板

    支持多个视图引擎

    JavaScript和Ajax

    模型验证改进

    MVC 2

    客户端验证

    模板化的助手

    区域

    异步控制器

    超文本标记语言ValidationSummary辅助方法

    动作方法参数中的DefaultValueAttribute

    使用模型绑定器绑定二进制数据

    DataAnnotations属性

    Model-Validator提供者

    新的RequireHttpsAttribute动作过滤器

    模板化的助手

    显示模型级错误

    MVC中的HTML助手是什么?

    HTML helper帮助您在视图中呈现HTML控件。例如,如果您想在视图上显示一个HTML文本框,下面是HTML帮助器代码。

    <%= Html.TextBox("LastName") %>

    对于复选框,下面是HTML帮助代码。通过这种方式,我们为每个存在的HTML控件都提供了HTML helper方法。

    <%= Html.CheckBox("Married") %>

    “HTML”之间的区别是什么?文本框”和“HTML.TextBoxFor”?

    它们都提供相同的HTML输出“HTML”。TextBoxFor“是强类型的,而”HTML。文本框”不是。下面是一个简单的HTML代码,它创建了一个简单的文本框,名称为“CustomerCode”。

    Html.TextBox("CustomerCode")

    下面是“Html。TextBoxFor "代码,它创建HTML文本框使用属性名' CustomerCode "从对象" m "。

    Html.TextBoxFor(m => m.CustomerCode)

    和其他HTML控件(如复选框)一样,我们有“HTML”。复选框”和“Html.CheckBoxFor”。

    MVC中的路由是什么?

    路由帮助您定义一个URL结构,并将该URL映射到控制器。

    例如,假设我们希望当用户键入“http://localhost/View/ViewCustomer/”时,它会转到“Customer”控制器并调用DisplayCustomer操作。这是通过使用maproute函数在路由集合中添加一个条目来定义的。下面是带下划线的代码,它显示了如何定义URL结构以及与控制器和动作的映射。

    routes.MapRoute(
                   "View", // Route name
                   "View/ViewCustomer/{id}", // URL with parameters
                   new { controller = "Customer", action = "DisplayCustomer", 
    id = UrlParameter.Optional }); // Parameter defaults   

    路线图编码写在哪里?

    路由映射代码以“RouteConfig”编写。文件,并使用“global”注册。应用程序启动事件。

    我们能把多个URL映射到同一个动作吗?

    可以,您只需要使用不同的键名创建两个条目,并指定相同的控制器和操作。

    解释基于属性的路由在MVC?

    这是MVC 5中引入的一个特性。通过使用“Route”属性,我们可以定义URL结构。例如,在下面的代码中,我们已经用route属性装饰了“GotoAbout”操作。route属性表示可以使用URL结构“Users/about”调用“GotoAbout”。

    public class HomeController : Controller
    {
           [Route("Users/about")]
           public ActionResult GotoAbout()
           {
               return View();
           }
    }

    在代码中定义路由结构的优点是什么?

    大多数时候,开发人员在操作方法中编写代码。开发人员可以直接看到URL结构,而不是去“routeconfig”。然后看看那些冗长的代码。例如,在下面的代码中,开发人员可以看到“GotoAbout”操作可以被四个不同的URL结构调用。

    与滚动浏览“routeconfig”相比,这更便于用户使用。文件,并通过代码的长度行找出哪个URL结构映射到哪个动作。

    public class HomeController : Controller
    {
           [Route("Users/about")]
           [Route("Users/WhoareWe")]
           [Route("Users/OurTeam")]
           [Route("Users/aboutCompany")]
           public ActionResult GotoAbout()
           {
               return View();
           }
    }

    如何使用超链接从一个视图导航到另一个视图?

    通过使用如下代码所示的ActionLink方法。下面的代码将创建一个简单的URL,它有助于导航到“Home”控制器并调用GotoHome操作。

    <%= Html.ActionLink("Home","Gotohome") %>  

    我们如何限制MVC操作只能被GET或POST调用?

    我们可以用HttpGet或HttpPost属性来装饰MVC操作,以限制HTTP调用的类型。例如,您可以在下面的代码片段中看到DisplayCustomer操作只能由HttpGet调用。如果我们尝试在DisplayCustomer上发布HTTP,它将抛出一个错误。

    [HttpGet]
    public ViewResult DisplayCustomer(int id)
    {
        Customer objCustomer = Customers[id];
        return View("DisplayCustomer",objCustomer);
    } 

    如何在MVC中维护会话?

    在MVC中可以通过三种方式维护会话:tempdata、viewdata和viewbag。

    tempdata、viewdata和viewbag之间有什么区别?

    Image 5

    图:tempdata、viewdata和viewbag的区别
    • Temp data—当您从一个控制器移动到另一个控制器或从一个动作移动到另一个动作时,帮助维护数据。换句话说,当您重定向时,tempdata帮助维护这些重定向之间的数据。它在内部使用会话变量。
    • 视图数据——当你从控制器移动到视图时,帮助维护数据。
    • 视图包-它是视图数据的动态包装器。当您使用Viewbag类型时,不需要强制转换。它在内部使用动态关键字。

    Image 6

    图:动态关键字
    • 会话变量——通过使用会话变量,我们可以维护从任何实体到任何实体的数据。
    • 隐藏字段和HTML控件——帮助维护从UI到控制器的数据。因此,您可以使用POST或GET HTTP方法将数据从HTML控件或隐藏字段发送到控制器。

    下面是一个汇总表,显示了不同的持久性机制。

    维护数据之间的viewdata / viewbag tempdata隐藏字段会话控制器到控制器,不,是,不是,是控制器来查看是否视图到控制器不,不,是,是

    TempData和ViewData之间有什么区别?

    “TempData”维护完整请求的数据,而“ViewData”只维护从控制器到视图的数据。

    “TempData”是否在下一个请求中保存数据?

    “TempData”在当前请求的out中可用,在随后的请求中可用,取决于是否读取“TempData”。

    因此,如果读取了一次“TempData”,那么在随后的请求中它将不可用。

    在“TempData”中使用Keep和Peek有什么用?

    在当前请求中读取“TempData”后,它在后续请求中不可用。如果我们想要读取“TempData”,并且在随后的请求中也可用,那么在读取之后,我们需要调用“Keep”方法,如下面的代码所示。

    @TempData["MyData"];
    TempData.Keep("MyData");

    更快捷的方法是使用“Peek”。这个函数帮助读取并通知MVC为后续请求维护“TempData”。

    string str = TempData.Peek("Td").ToString();

    如果你想阅读更多的细节,你可以阅读这个关于MVC Peek和Keep的详细博客。

    什么是MVC中的部分视图?

    部分视图是可重用的视图(像用户控件),可以嵌入到其他视图中。例如,假设您的站点的所有页面都有一个标准的结构,包括左侧菜单、页眉和页脚,如下图所示。

    Image 7

    图:MVC中的部分视图

    对于希望重用左侧菜单、页眉和页脚控件的每个页面。你可以为每一项创建部分视图然后在主视图中调用那个部分视图。

    如何创建和使用部分视图?

    当您向您的项目添加视图时,您需要选中“创建部分视图”复选框。

    Image 8

    图:创建部分视图

    一旦创建了部分视图,您就可以使用Html在主视图中调用部分视图。RenderPartial方法如下代码片段所示:

    <body>
    <div>
    <% Html.RenderPartial("MyView"); %>
    </div>
    </body> 

    如何在MVC中进行验证?

    在MVC中进行验证的最简单方法之一是使用数据注释。数据注释只是可以应用于模型属性的属性。例如,在下面的代码片段中,我们有一个带有customercode属性的简单Customer类。

    这个CustomerCode属性被标记为一个必需的数据注释属性。换句话说,如果这个模型没有提供客户代码,它将不会接受它。

    public class Customer
    {
        [Required(ErrorMessage="Customer code is required")]
        public string CustomerCode
        {
            set;
            get;
        } 
    }  

    为了显示验证错误消息,我们需要使用ValidateMessageFor方法,它属于Html helper类。

    <% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
    { %>
    <%=Html.TextBoxFor(m => m.CustomerCode)%>
    <%=Html.ValidationMessageFor(m => m.CustomerCode)%>
    <inputtype="submit"value="Submit customer data"/>
    <%}%> 

    稍后在控制器中,我们可以使用ModelState检查模型是否正确。是有效的财产,因此我们可以采取行动。

    public ActionResult PostCustomer(Customer obj)
    {
        if (ModelState.IsValid)
        {
            obj.Save();
            return View("Thanks");
        }
        else
        {
            return View("Customer");
        }
    }

    下面是如何在视图中显示错误消息的简单视图。

    Image 9

    图:MVC中的验证

    我们能一次显示所有的错误吗?

    是的,我们能;使用Html helper类中的ValidationSummary方法。

    <%= Html.ValidationSummary() %>   

    MVC中用于验证的其他数据注释属性是什么?

    如果要检查字符串长度,可以使用StringLength。

    [StringLength(160)]
    public string FirstName { get; set; }

    如果希望使用正则表达式,可以使用RegularExpression属性。

    [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}")]public string Email { get; set; }

    如果要检查数字是否在范围内,可以使用range属性。

    [Range(10,25)]public int Age { get; set; }

    有时您想比较一个字段和另一个字段的值,我们可以使用compare属性。

    public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }

    如果您希望获得一个特定的错误消息,您可以使用Errors集合。

    var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

    如果您自己创建了模型对象,您可以显式地在控制器中调用TryUpdateModel来检查对象是否有效。

    TryUpdateModel(NewCustomer);

    如果你想在控制器中添加错误,你可以使用AddModelError函数。

    ModelState.AddModelError("FirstName", "This is my server-side error.");

    如何在客户端启用数据注释验证?

    这个过程分为两步:首先引用必要的jQuery文件。

    <scriptsrc="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>"type="text/javascript"></script>
    <scriptsrc="<%= Url.Content("~/Scripts/jquery.validate.js") %>"type="text/javascript"></script>
    <scriptsrc="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>"type="text/javascript"></script> 

    第二步是调用EnableClientValidation方法。

    <% Html.EnableClientValidation(); %> 

    MVC中的Razor是什么?

    这是一个轻量级视图引擎。在MVC之前,我们只有一种视图类型。ASPX。Razor是在MVC 3中引入的。

    既然已经有了ASPX,为什么还要剃须刀?

    与ASPX相比,Razor干净、轻便、语法简单。例如,在ASPX中显示简单的时间,我们需要写:

    <%=DateTime.Now%> 

    在Razor中,只有一行代码:

    @DateTime.Now

    那么剃须刀和ASPX哪个更合适呢?

    按照微软的说法,Razor更受青睐,因为它重量轻,语法简单。

    如何在MVC中进行身份验证和授权?

    可以对MVC使用Windows或窗体身份验证。

    如何实现MVC的Windows认证?

    对于Windows身份验证,您需要修改web。配置文件,并将身份验证模式设置为Windows。

    <authenticationmode="Windows"/>
    <authorization>
    <denyusers="?"/>
    </authorization> 

    然后,在控制器或操作上,您可以使用Authorize属性,该属性指定哪些用户可以访问这些控制器和操作。下面是它的代码片段。现在只有在控制器和操作中指定的用户可以访问它。

    [Authorize(Users= @"WIN-3LI600MWLQNAdministrator")]
    public class StartController : Controller
    {
        //
        // GET: /Start/
        [Authorize(Users = @"WIN-3LI600MWLQNAdministrator")]
        public ActionResult Index()
        {
            return View("MyView");
        }
    } 

    如何在MVC中实现表单身份验证?

    表单身份验证的实现方式与ASP.NET相同。第一步是将身份验证模式设置为等于Forms。loginUrl在这里指向一个控制器,而不是页面。

    <authenticationmode="Forms">
    <formsloginUrl="~/Home/Login"timeout="2880"/>
    </authentication> 

    我们还需要创建一个控制器,用于检查用户是否正确。如果用户是正确的,我们将设置cookie的值。

    public ActionResult Login()
    {
        if ((Request.Form["txtUserName"] == "Shiv") && 
              (Request.Form["txtPassword"] == "Shiv@123"))
        {
            FormsAuthentication.SetAuthCookie("Shiv",true);
            return View("About");
        }
        else
        {
            return View("Index");
        }
    } 

    所有其他操作都需要使用Authorize属性,这样任何调用这些控制器的未授权用户都将被重定向到控制器(在本例中控制器是“Login”),该控制器将执行身份验证。

    [Authorize]
    PublicActionResult Default()
    {
    return View();
    }
    [Authorize]
    publicActionResult About()
    {
    return View();
    } 

    如何在MVC中实现AJAX ?

    你可以在MVC中以两种方式实现AJAX:

    • AJAX库
    • jQuery

    下面是一个使用“AJAX”助手库实现AJAX的简单示例。在下面的代码中,您可以看到我们使用Ajax创建了一个简单的表单。BeginForm语法。这个表单调用一个名为getCustomer的控制器操作。因此,现在单击submit动作将是一个异步AJAX调用。

    <script language="javascript">
    function OnSuccess(data1) 
    {
    // Do something here
    }
    </script>
    <div>
    <%
            var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};        
        %>
    <% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
    <input id="txtCustomerCode" type="text" /><br />
    <input id="txtCustomerName" type="text" /><br />
    <input id="Submit2" type="submit" value="submit"/></div>
    <%} %> 

    如果希望在超链接单击时进行AJAX调用,可以使用AJAX。ActionLink函数如下面的代码所示。

    Image 10

    图:在MVC中实现AJAX

    如果你想创建一个名为GetDate的AJAX异步超链接它在控制器中调用GetDate函数,下面是代码。控制器响应后,该数据将显示在名为DateDiv的HTML DIV标记中。

    <spanid="DateDiv"/>
    <%: 
    Ajax.ActionLink("Get Date","GetDate",
    new AjaxOptions {UpdateTargetId = "DateDiv" })
    %> 

    下面是控制器代码。您可以看到GetDate函数如何有10秒的暂停。

    public class Default1Controller : Controller
    {
       public string GetDate()
       {
           Thread.Sleep(10000);
           return DateTime.Now.ToString();
       }
    }

    在MVC中进行AJAX调用的第二种方法是使用jQuery。在下面的代码中,您可以看到我们正在对URL /MyAjax/getCustomer进行AJAX POST调用。这是通过使用$.post完成的。所有这些逻辑都被放入一个名为GetData的函数中,您可以根据需要在按钮或超链接单击事件上调用GetData函数。

    function GetData() 
    {
        var url = "/MyAjax/getCustomer";
        $.post(url, function (data) 
        {
            $("#txtCustomerCode").val(data.CustomerCode);
            $("#txtCustomerName").val(data.CustomerName);
        }
        )
    } 

    AJAX中可以跟踪什么类型的事件?

    Image 11

    图:在AJAX中跟踪

    ActionResult和ViewResult之间的区别是什么?

    • ActionResult是一个抽象类,而ViewResult派生自ActionResult类。ActionResult有几个派生类,如ViewResult、JsonResult、FileStreamResult等。
    • ActionResult可用于利用多态和动态性。如果你动态返回不同类型的视图,ActionResult是最好的选择。例如,在下面的代码片段中,您可以看到我们有一个名为DynamicView的简单操作。根据标志(IsHtmlView),它将返回一个ViewResult或JsonResult。
    public ActionResult DynamicView()
    {
       if (IsHtmlView)
         return View(); // returns simple ViewResult
       else
         return Json(); // returns JsonResult view
    } 

    在MVC中有哪些不同类型的结果?

    注意:要记住所有的12种类型是很困难的。但是您可以记住一些重要的内容,它们是ActionResult、ViewResult和JsonResult。以下是您感兴趣的详细列表:

    在MVC中有12种结果,顶部是ActionResult类,它是一个基类,可以有11个子类型,如下所示:

      ViewResult——呈现视图指定响应流partialviewresult——指定局部视图呈现响应流emptyresult -返回一个空响应redirectresult执行HTTP重定向到指定的网址redirecttorouteresult执行HTTP重定向到一个网址,是由路由引擎,基于给定的路线数据jsonresult——给定可视数据对象序列化JSON格式javascriptresult——返回的JavaScript代码可以在客户机上执行contentresult——将内容写入响应流而不需要一个视图filecontentresult -返回一个文件到客户端filestreamresult返回一个文件到客户端,提供的是一个流filepathresult -将文件返回给客户端

    MVC中的ActionFilters是什么?

    ActionFilters帮助您在MVC操作正在执行时或在MVC操作已经执行后执行逻辑。

    Image 12

    图:MVC中的ActionFilters

    动作过滤器在以下场景中非常有用:

      在动作发生之前实现后处理逻辑。取消当前执行。检查返回值。为操作提供额外的数据。

    你可以通过两种方式创建动作过滤器:

    • 内联行动过滤器。
    • 创建一个ActionFilter属性。

    为了创建一个内联操作属性,我们需要实现IActionFilter接口。IActionFilter接口有两个方法:OnActionExecuted和onactionexecution。我们可以在这些方法中实现预处理逻辑或取消逻辑。

    public class Default1Controller : Controller , IActionFilter
    {
        public ActionResult Index(Customer obj)
        {
            return View(obj);
        }
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Trace.WriteLine("Action Executed");
        }
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            Trace.WriteLine("Action is executing");
        }
    } 

    内联动作属性的问题是它不能跨控制器重用。因此,我们可以将内联操作过滤器转换为操作过滤器属性。要创建一个action filter属性,我们需要从ActionFilterAttribute继承并实现IActionFilter接口,如下面的代码所示。

    public class MyActionAttribute : ActionFilterAttribute , IActionFilter
    {
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Trace.WriteLine("Action Executed");
        }
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
          Trace.WriteLine("Action executing");
        }
    } 

    稍后,我们可以修饰要在其上执行动作属性的控制器。您可以在下面的代码中看到,我用在前面代码中创建的MyActionAttribute类装饰了Default1Controller。

    [MyActionAttribute]
    public class Default1Controller : Controller 
    {
        public ActionResult Index(Customer obj)
        {
            return View(obj);
        }
    }

    动作过滤器有哪些不同类型?

      授权筛选、操作筛选、结果筛选、异常筛选

    如果我们有多个过滤器,执行的顺序是什么?

      授权筛选器操作筛选器响应筛选器异常筛选器

    我们可以使用MVC创建我们的自定义视图引擎吗?

    是的,我们可以在MVC中创建自己的自定义视图引擎。要创建我们自己的自定义视图引擎,我们需要遵循三个步骤:

    假设我们想要创建一个自定义的视图引擎,在其中用户可以键入一个命令,如“<DateTime>”,它应该显示当前的日期和时间。

    步骤1:我们需要创建一个实现IView接口的类。在这个类中,我们应该编写如何在render函数中呈现视图的逻辑。下面是一个简单的代码片段。

    public class MyCustomView : IView
    {
        private string _FolderPath; // Define where  our views are stored
        public string FolderPath
        {
            get { return _FolderPath; }
            set { _FolderPath = value; }
        }
    
        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
           // Parsing logic <dateTime>
            // read the view file
            string strFileData = File.ReadAllText(_FolderPath);
            // we need to and replace <datetime> datetime.now value
            string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString());
            // this replaced data has to sent for display
            writer.Write(strFinal); 
        }
    } 

    步骤2:我们需要创建一个继承自VirtualPathProviderViewEngine的类,在这个类中,我们需要提供文件夹路径和视图名的扩展名。例如,Razor的扩展名是“cshtml”;对于aspx,视图扩展名是“。因此,就像我们的自定义视图一样,我们需要提供一个扩展。下面是代码的样子。你可以看到ViewLocationFormats被设置为Views文件夹,扩展名是“。myview”。

    public class MyViewEngineProvider : VirtualPathProviderViewEngine
    {
        // We will create the object of Mycustome view
        public MyViewEngineProvider() // constructor
        {
            // Define the location of the View file
            this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", 
              "~/Views/Shared/{0}.myview" }; //location and extension of our views
        }
        protected override IView CreateView(
          ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine class
            obj.FolderPath = physicalpath; // set the path where the views will be stored
            return obj; // returned this view paresing
            // logic so that it can be registered in the view engine collection
        }
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine class
            obj.FolderPath = physicalpath; // set the path where the views will be stored
            return obj;
            // returned this view paresing logic
            // so that it can be registered in the view engine collection
        }
    } 

    步骤3:我们需要在自定义视图集合中注册视图。在viewengine集合中注册自定义视图引擎的最佳位置是全局视图。asax文件。下面是它的代码片段。

    protected void Application_Start()
    {
        // Step3 :-  register this object in the view engine collection
        ViewEngines.Engines.Add(new MyViewEngineProvider());
        …..
    } 

    下面是使用顶部定义的命令编写的自定义视图的简单输出。

    Image 13

    图:使用MVC自定义视图引擎

    如果调用这个视图,应该会看到以下输出:

    Image 14

    如何发送结果返回JSON格式在MVC

    在MVC中,我们有JsonResult类,通过它我们可以返回JSON格式的数据。下面是一个简单的示例代码,它使用JsonResult返回一个JSON格式的Customer对象。

    public JsonResult getCustomer()
    {
        Customer obj = new Customer();
        obj.CustomerCode = "1001";
        obj.CustomerName = "Shiv";
        return Json(obj,JsonRequestBehavior.AllowGet);
    }

    如果您通过浏览器调用操作,下面是上述代码的JSON输出。

    Image 15

    之前是什么?

    HTTP是最常用的协议。在过去的许多年里,browser是我们使用通过HTTP公开的数据的首选客户机。但随着时间的推移,客户种类开始增多。我们需要从移动、JavaScript、Windows应用程序等客户端使用HTTP上的数据。

    为了满足广泛的客户,REST是被提议的方法。你可以从WCF章节中了解更多关于REST的内容。

    通过WebAPI,您可以遵循REST原则通过HTTP公开数据。

    但是WCF SOAP也做同样的事情,那么WebAPI有什么不同呢?

    ,soap web API由于WSDL结构复杂,所以大小很重要。重量轻,只传送必要的信息。协议独立于协议。只适用于HTTP协议要解析SOAP消息,客户端需要理解WSDL格式。编写用于解析WSDL的自定义代码是一项繁重的任务。如果您的客户端足够聪明,能够像我们在。net(添加引用)中那样创建代理对象,那么SOAP就更容易使用和调用。WebAPI的输出是简单的字符串消息、JSON、简单的XML格式等等。所以为它编写解析逻辑是很容易的。soap遵循WS-*规范的原则。WebAPI遵循REST原则。(请参考WCF章节中的REST)

    有了WCF,你可以实现REST,那为什么是WebAPI呢?

    WCF被用于实现SOA,其目的绝不是实现REST。WebAPI是从头开始构建的,唯一的目标是使用REST创建HTTP服务。由于创建REST服务的焦点是一点,所以更倾向于使用WebAPI。

    如何在MVC中实现WebAPI

    下面是实现WebAPI的步骤:

    步骤1:使用WebAPI模板创建项目。

    Image 16

    图:在MVC中实现WebAPI

    步骤2:一旦您创建了项目,您将注意到控制器现在继承了ApiController,您现在可以实现HTTP协议的POST、GET、PUT和DELETE方法。

    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }
        // POST api/values
        public void Post([FromBody]string value)
        {
        }
        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    } 

    步骤3:如果你做一个HTTP GET调用,你应该得到以下结果:

    Image 17

    图:HTTP

    我们如何检测一个MVC控制器被POST或GET调用?

    为了检测对控制器的调用是POST操作还是GET操作,我们可以使用请求。属性,如下面的代码片段所示。

    public ActionResult SomeAction()
    {
        if (Request.HttpMethod == "POST")
        {
            return View("SomePage");
        }
        else
        {
            return View("SomeOtherPage");
        }
    }

    什么是MVC中的绑定和缩小?

    捆绑和缩小可以帮助我们改进页面的请求加载时间,从而提高性能。

    捆绑是如何提高性能的?

    Web项目总是需要CSS和脚本文件。捆绑帮助我们将多个JavaScript和CSS文件合并到一个实体中,从而将多个请求减少到一个请求中。

    例如,考虑下面对页面的web请求。这个页面使用两个JavaScript文件Javascript1.js和Javascript2.js。所以当这个页面被请求时,它发出三个请求调用:

    • 一个用于索引页。
    • 另外两个JavaScript文件的请求:Javascript1.js和Javascript2.js。

    如果我们有很多JavaScript文件导致多个请求,从而降低性能,那么下面的场景会变得更糟。如果我们能以某种方式将所有的JS文件合并到一个包中,并将它们作为一个单元来请求,将会提高性能(见下一幅图,其中有一个请求)。

    Image 18

    Image 19

    如何在MVC中实现绑定呢?

    从App_Start文件夹打开BundleConfig.cs。

    Image 20

    在BundleConfig。cs,将你想要捆绑成一个实体的JS文件添加到bundle集合中。在下面的代码中,我们将存在于Scripts文件夹中的所有javascript JS文件作为单个单元合并到bundle集合中。

    bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
    "~/Scripts/*.js")); 

    下面是你的BundleConfig.cs文件的样子:

    public  class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
               "~/Scripts/*.js"));
            BundleTable.EnableOptimizations = true;
        }
    }

    一旦你把你的脚本合并到一个单元中,我们就可以使用下面的代码将所有的JS文件包含到视图中。下面的代码需要放在ASPX或Razor视图中。

    <%= Scripts.Render("~/Scripts/MyScripts")  %>

    如果您现在看到您的页面请求,您将看到脚本请求被合并到一个请求中。

    Image 21

    如何在调试模式下测试绑定?

    如果处于调试模式,则需要在bundleconfig文件中将EnableOptimizations设置为true,否则将不会在页面请求中看到绑定效果。

    BundleTable.EnableOptimizations = true;

    解释缩小和如何实现它

    通过删除空白、注释等,缩小脚本和CSS文件的大小。例如,下面是一个带有注释的简单javascript代码。

    // This is test
    var x = 0;
    x = x + 1;
    x = x * 2;

    实现了缩小后,JavaScript代码如下所示。您可以看到如何删除空白和注释以最小化文件大小,从而提高性能。

    var x=0;x=x+1;x=x*2;

    我们如何实现缩小?

    在实现绑定时,缩小是自己实现的。换句话说,实现绑定和缩小的步骤是相同的。

    解释MVC中的区域?

    区域可以帮助您将功能分组到独立的模块中,从而使您的项目更有组织。例如,在下面的MVC项目中,我们有四个控制器类,随着时间的推移,如果添加了更多的控制器类,将很难管理。在更大的项目中,您将以100个控制器类使维护工作变得非常困难而告终。

    Image 22

    如果我们可以将控制器类分组到像“发票”和“会计”这样的逻辑部分中,这将使生活更容易,这就是“Area”的意思。

    Image 23

    您可以通过右键单击MVC解决方案并单击“area”菜单来添加一个区域,如下图所示。

    Image 24

    在下面的图像中,我们有两个“区域”创建“帐户”和“发票”,在那里我已经把各自的控制器。您可以看到,与以前的状态相比,项目看起来更有组织性。

    Image 25

    ,

    解释MVC中视图模型的概念?

    视图模型是一个简单的类,它表示要在视图上显示的数据。

    例如,下面是一个简单的customermodel对象,它具有“CustomerName”和“Amount”属性。

    CustomerViewModel obj = new CustomerViewModel();
    obj.Customer.CustomerName = "Shiv";
    obj.Customer.Amount = 1000;

    但是当这个“Customer”模型对象显示在MVC视图上时,它看起来如下图所示。在视图/屏幕上有“CustomerName”、“Amount”和“Customer purchase Level”字段。“顾客购买水平”是一种颜色指标,表明顾客购买的积极性。

    “客户购买水平”的颜色取决于“金额属性”的价值。如果数量大于2000,则颜色为红色,如果数量大于1500,则颜色为橙色,否则颜色为黄色。

    换句话说,“客户购买水平”是一个额外的财产,以数量为基础计算。

    Image 26

    因此,Customer viewmodel类有三个属性

    • “TxtCustomerName”文本框按原样从“CustomerName”属性获取数据。
    • “TxtAmount”文本框按原样从模型的“Amount”属性获取数据。
    • “CustomerBuyingLevelColor”根据“Amount”值显示颜色值。
    客户模型客户视图模型customername txtcustomernametxtamount数量,CustomerBuyingLevelColor

    模型类将拥有什么样的逻辑视图?

    顾名思义,视图模型这个类有连接视图和模型的gel代码或连接代码。

    因此视图模型类可以有以下逻辑:-

    • 颜色转换逻辑:-例如你在模型中有一个“等级”属性,你想让你的UI显示“红色”表示高级等级,“黄色”表示低级等级,“绿色”表示ok等级。
    • 数据格式转换逻辑:-你的模型有一个属性Status,值为“已婚”和“未婚”。在UI中,你想把它显示为一个复选框,如果“已婚”选中,如果“未婚”不选中。
    • 聚合逻辑:您有两个不同的Customer和Address模型类,并且您有一个同时显示“Customer”和“Address”数据的视图。
    • Structure downsizing: - You have “Customer” model with “customerCode” and “CustomerName” and you want to display just “CustomerName”. So you can create a wrapper around model and expose the necessary properties.

      How can we use two ( multiple) models with a single view?

      Let us first try to understand what the interviewer is asking. When we bind a model with a view we use the model dropdown as shown in the below figure. In the below figure we can only select one model.

      Image 27ggimggg0

      But what if we want to bind “Customer” as well as “Order” class to the view.

      For that we need to create a view model which aggregates both the classes as shown in the below code. And then bind that view model with the view.

      public class CustOrderVM
      {
      public  Customer cust = new Customer();
      public Order Ord = new Order();
      }

      In the view we can refer both the model using the view model as shown in the below code.

      <%= model.cust.Name %>
      <%= model.Ord.Number %>

      Explain the need of display mode in MVC?

      Display mode displays views depending on the device the user has logged in with. So we can create different views for different devices anddisplay mode will handle the rest.

      For example we can create a view “Home.aspx” which will render for the desktop computers and Home.Mobile.aspx for mobile devices. Now when an end user sends a request to the MVC application, display mode checks the “user agent” headers and renders the appropriate view to the device accordingly.

      Image 28ggimggg1

      Explain MVC model binders?

      Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model. Many times HTML UI names are different than the model property names. So in the binder we can write the mapping logic between the UI and the model.

      Image 29ggimggg2

      Explain the concept of MVC Scaffolding?

      Note :- Do not get scared with the word. Its actually a very simple thing.

      Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for create, read, update and delete.

      So to generate code using scaffolding technique we need to select one of the types of templates (leave the empty one).

      Image 30ggimggg3

      For instance if you choose “using Entity framework” template the following code is generated.

      Image 31ggimggg4

      It creates controller code, view and also table structure as shown in the below figure.

      Image 32ggimggg5

      What does scaffolding use internally to connect to database?

      It uses Entity framework internally.

      How can we do exception handling in MVC?

      In the controller you can override the “OnException” event and set the “Result” to the view name which you want to invoke when error occurs. In the below code you can see we have set the “Result” to a view named as “Error”.

      We have also set the exception so that it can be displayed inside the view.

      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)
           };
      
              }
      }

      To display the above error in view we can use the below code

      @Model.Exception;
      

      How can you handle multiple Submit buttons pointing to multiple actions in a single MVC view?

      Let us elaborate on what the interviewer wants to ask because the above question is just a single liner and is not clear about what the interviewer wants.

      Take a scenario where you have a view with two submit buttons as shown in the below code.

      <form action="Action1" method=post>
      <input type="submit" name="Submit1"/>
      <input type="submit" name="Submit2">
      </form>

      In the above code when the end user clicks on any of the submit buttons it will make a HTTP POST to “Action1”.

      The question from the interviewer is:-

      “What if we have want that on “Submit1” button click it should invoke “Action1” and on the “Submit2” button click it should invoke “Action2”.”

      Now that we have understood the question let us answer the question in a detailed manner. There are two approaches to solve the above problem one is the normal HTML way and the other is the “Ajax” way.

      In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Action1” and the second form will post to “Action2” depending on which “Submit” button is clicked.

      <form action="Action1" method=post>
      <input type="submit" name="Submit1"/>
      </form>
      
      <form action="Action2" method=post>
      <input type="submit" name="Submit2">
      </form>

      In case the interviewer complains that the above approach is not AJAX this is where the second approach comes in. In the Ajax way we can create two different functions “Fun1” and “Fun1” , see the below code. These function will make Ajax calls by using JQUERY or any other framework. Each of these functions are binded with the “Submit” button’s “OnClick” events.

      <Script language=javascript>
      function Fun1()
      {
      $.post("/Action1",null,CallBack1);
      }
      function Fun2()
      {
      $.post("/Action2",null,CallBack2);
      }
      </Script>
      <form action="/Action1" method=post>
      <input type=submit name=sub1 onclick="Fun2()"/>
      </form>
      <form action="/Action2" method=post>
      <input type=submit name=sub2 onclick="Fun1()"/>
      </form>

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

      CSRF stands for Cross site request forgery. So if you see the dictonary meaning of forgery: -

      “It’s an act of copying or imitating things like signature on a cheque, official documents to deceive the authority source for financial gains.”

      So when it comes to website this forgery is termed as CSRF (Cross Site Request Forgery).

      CSRF is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. Genuine site processes the information innocently thinking that data is coming from a trusted source.

      For example conside the below screen of a online bank. End user’s uses this screen to transfer money.

      Image 33ggimggg6

      Below is a forged site created by an attacker which looks a game site from outside, but internally it hits the bank site for money transfer.

      Image 34ggimggg7

      The internal HTML of the forged site has those hidden fields which have the account number and amount to do money transfer.

       
      Win 1000000 US$ <form action="http://localhost:23936/Genuine/Transfer" method=post> <input type=hidden name="amount" value="10000" /> <input type=hidden name="account" value="3002" /> <input type=submit value="Play the ultimate game" /> </form>

      Now let’s say the user has logged in to the genuine bank site and the attacker sent this forged game link to his email. The end user thinking that it’s a game site clicks on the “Play the Ultimate Game” button and internally the malicious code does the money transfer process.

      Image 35ggimggg8

      So a proper solution to this issue can be solved by using tokens: -

      • End user browses to the screen of the money transfer. Before the screen is served server injects a secret token inside the HTML screen in form a hidden field.
      • Now hence forth when the end user sends request back he has to always send the secret token. This token is validated on the server.

      Image 36ggimggg9

      Implementing token is a two-step process in MVC: -

      First apply “ValidateAntiForgeryToken” attribute on the action.

      [ValidateAntiForgeryToken]
      public ActionResult Transfer()
      {
                  // password sending logic will be here
                  return Content(Request.Form["amount"] + 
                      " has been transferred to account " 
                      + Request.Form["account"]);
      }

      Second in the HTML UI screen call “@Html.AntiForgeryToken()” to generate the token.

       
      Transfer money <form action="Transfer" method=post> Enter Amount <input type="text" name="amount" value="" />
      Enter Account number
      @Html.AntiForgeryToken() <input type=submit value="transfer money" /> </form>

      So now henceforth when any untrusted source send a request to the server it would give the below forgery error.

      Image 37ggimggg10

      If you do a view source of the HTML you would find the below verification token hidden field with the secret key.

      <inputname="__RequestVerificationToken"type="hidden"value="7iUdhsDNpEwiZFTYrH5kp/q7jL0sZz+CSBh8mb2ebwvxMJ3eYmUZXp+uofko6eiPD0fmC7Q0o4SXeGgRpxFp0i+Hx3fgVlVybgCYpyhFw5IRyYhNqi9KyH0se0hBPRu/9kYwEXXnVGB9ggdXCVPcIud/gUzjWVCvU1QxGA9dKPA="/>
      Please do read this blog which has detailed steps of how model binders can be created using “IModelBinder” interface: - Explain MVC model Binders?

      Download an e-learning copy of MVC interview Q&A from the top of this article for your preparation.

      For technical training related to various topics including ASP.NET, Design Patterns, WCF, MVC, BI, WPF contact SukeshMarla@gmail.com or visit www.sukesh-marla.com

      Finally do not forget to visit my video site which covers lots of C# interview questions and answers: www.questpond.com.

    本文转载于:http://www.diyabc.com/frontweb/news14840.html

  • 相关阅读:
    Wedding(2-SAT)
    JSOI2010 满汉全席
    2-SAT问题
    Tarjan求桥
    遥远的国度
    NOIP2014 联合权值
    部落冲突
    仓鼠找sugar
    2018.09.09 DL24 Day2总结
    php一些易犯的错误
  • 原文地址:https://www.cnblogs.com/Dincat/p/13488449.html
Copyright © 2011-2022 走看看