哪个是重定向网址的最佳方式?我们应该使用Response.Redirect还是还有其他任何重定向命令?

时间:2016-06-28 17:19:13

标签: c# asp.net-mvc

我是Csharp ASP.NET和MVC的新手。我试图自定义登录页面,并试图保持一个条件检查登录是否经过身份验证。如果登录完成,那么下次用户进入 url: localhost:portno/account/login ,网址将定向到localhost:portno/home/index。我使用了

的Respond.Redirect方法
@model LearningMvc.Models.LoginViewModel 

完整代码如下:

    @model LearningMvc.Models.LoginViewModel

@{
    ViewBag.Title = "Log in";
}

<h2>@ViewBag.Title.</h2>
<div class="row">
    <div class="col-md-8">
        <section id="loginForm">
            @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                if (Request.IsAuthenticated)
                    {
                        Response.Redirect("~/home/index");
    }
                else { 
                        <h4>Use a local account to log in.</h4>
                    <hr />
                    @Html.ValidationSummary(true)
                    <div class="form-group">
                        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
                            @Html.ValidationMessageFor(m => m.UserName)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.Password)
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <div class="checkbox">
                            @Html.CheckBoxFor(m => m.RememberMe)
                            @Html.LabelFor(m => m.RememberMe)
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Log in" class="btn btn-default" />
                    </div>
                </div>
                <p>
                    @Html.ActionLink("Register", "Register") if you don't have a local account.
                </p>
            }
            }
        </section>
    </div>
    <div class="col-md-4">
        <section id="socialLoginForm">
            @Html.Partial("_ExternalLoginsListPartial", new { Action = "ExternalLogin", ReturnUrl = ViewBag.ReturnUrl })
        </section>
    </div>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

我关心的只是功能

if (Request.IsAuthenticated)
                    {
                        Response.Redirect("~/home/index");
    }
                else {}

当我在Web浏览器中运行代码时,我在Visual Studio中得到一个异常,如下所述:

    System.Web.HttpException was unhandled by user code
    HResult=-2147467259
    Message=Server cannot append header after HTTP headers have been sent.
    Source=System.Web
    ErrorCode=-2147467259
    WebEventCode=0
    StackTrace:
       at System.Web.HttpResponse.AppendHeader(String name, String value)
       at System.Web.HttpResponse.AddHeader(String name, String value)
       at System.Web.HttpResponseWrapper.AddHeader(String name, String value)
       at System.Web.Helpers.AntiXsrf.AntiForgeryWorker.GetFormInputElement(HttpContextBase httpContext)
       at System.Web.Helpers.AntiForgery.GetHtml()
       at System.Web.Mvc.HtmlHelper.AntiForgeryToken()
       at ASP._Page_Views_Shared__LoginPartial_cshtml.Execute() in c:\Users\Sanjog Sigdel\Documents\Visual Studio 2013\Projects\LearningMvc\LearningMvc\Views\Shared\_LoginPartial.cshtml:line 6
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
       at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
       at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
       at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
       at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection)
       at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData)
       at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName)
       at ASP._Page_Views_Shared__Layout_cshtml.Execute() in c:\Users\Sanjog Sigdel\Documents\Visual Studio 2013\Projects\LearningMvc\LearningMvc\Views\Shared\_Layout.cshtml:line 28
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
       at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer)
       at System.Web.WebPages.WebPageBase.<>c__DisplayClass7.<RenderPageCore>b__6(TextWriter writer)
       at System.Web.WebPages.HelperResult.WriteTo(TextWriter writer)
       at System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content)
       at System.Web.WebPages.WebPageBase.Write(HelperResult result)
       at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body)
       at System.Web.WebPages.WebPageBase.PopContext()
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
       at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
       at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
       at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
  InnerException: 

在visual Studio中按下“继续”后代码正常工作。 是什么创造了这个例外?

1 个答案:

答案 0 :(得分:10)

你不应该在你的视图中做任何非表示逻辑!!这绝不应该在视野中:

if (Request.IsAuthenticated)
{
  Response.Redirect("~/home/index");
}

问题的存在是因为视图正在执行,并且已经发送了有关响应类型的标题(在本例中为text / html)。

逻辑应该在控制器中:

public ActionResult MyAction()
{
  /// ... code

  if (Request.IsAuthenticated)
  {
    return RedirectToAction("index", "home");
  }

  return View();
}