简体   繁体   English

哪种是重定向URL的最佳方法? 我们应该使用Response.Redirect还是有其他用于重定向的命令?

[英]Which is the best way to redirect URL? Should we be using Response.Redirect or are there any other commands for redirecting?

I'm new to Csharp ASP.NET and MVC. 我是Csharp ASP.NET和MVC的新手。 I'm trying to customize the login page and was trying to keep a condition which would 我正在尝试自定义登录页面,并试图保持某种状态
Check if the Login is Authenticated or not. 检查登录名是否已通过身份验证。 If login is done then next time while the user enters the url: localhost:portno/account/login the url will be directed to localhost:portno/home/index . 如果登录完成,则下次用户输入url: localhost:portno/account/login该URL将定向到localhost:portno/home/index I used Respond.Redirect methon using 我使用了Respond.Redirect methon

@model LearningMvc.Models.LoginViewModel 

Full code is mentioned below: 完整代码如下:

    @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")
}

My concern is with only the function 我只关心功能

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

As I run the code in web browser I get an exception in Visual studio which is mentioned below: 当我在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: 

The code works after I press continue in visual Studio. 在Visual Studio中按“继续”后,代码将起作用。 What is creating that exception? 是什么造成了这种例外?

You should not be doing any non-presentation logic in your view!! 您不应在视图中进行任何非表示逻辑!! This should never be in a view: 永远不要这样认为:

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

The problem exists because the view is executing and it's already sent headers about the response type (text/html in this case). 存在该问题是因为视图正在执行,并且已经发送了有关响应类型的标头(在这种情况下为text / html)。

Instead your logic should be in the controller: 相反,您的逻辑应该在控制器中:

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

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

  return View();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM