30

在我的网络应用程序中,我正在验证来自 glabal.asax 的 url。我想验证 url,如果需要,需要重定向到一个动作。我正在使用 Application_BeginRequest 来捕获请求事件。

  protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // If the product is not registered then
        // redirect the user to product registraion page.
        if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
        {
             //HOW TO REDIRECT TO ACTION (action=register,controller=product)
         }
     }

或者是否有任何其他方法可以在 mvc 中获取请求并在需要时重定向到操作时验证每个 url

4

9 回答 9

29

以上所有都行不通,您将处于执行方法的循环中Application_BeginRequest

你需要使用

HttpContext.Current.RewritePath("Home/About");
于 2014-09-11T10:49:22.890 回答
25

使用以下代码进行重定向

   Response.RedirectToRoute("Default");

“默认”是路线名称。如果您想重定向到任何操作,只需创建一个路由并使用该路由名称。

于 2011-10-05T06:26:48.310 回答
14

除了已经提到的方式。另一种方法是使用 URLHelper,一旦发生错误,我在场景中使用它,用户应该被重定向到登录页面:

public void Application_PostAuthenticateRequest(object sender, EventArgs e){
    try{
         if(!Request.IsAuthenticated){
            throw  new InvalidCredentialException("The user is not authenticated.");
        }
    } catch(InvalidCredentialException e){
        var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
        Response.Redirect(urlHelper.Action("Login", "Account"));
    }
}
于 2016-05-12T00:25:48.407 回答
6

试试这个:

HttpContext.Current.Response.Redirect("...");
于 2011-08-16T16:43:53.550 回答
4

我这样做:

        HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", "Home");
        routeData.Values.Add("action", "FirstVisit");

        IController controller = new HomeController();

        RequestContext requestContext = new RequestContext(contextWrapper, routeData);

        controller.Execute(requestContext);
        Response.End();

这样,您可以包装传入的请求上下文并将其重定向到其他地方,而无需重定向客户端。所以重定向不会触发 global.asax 中的另一个 BeginRequest。

于 2015-06-02T14:03:53.870 回答
0
 Response.RedirectToRoute(
                                new RouteValueDictionary {
                                    { "Controller", "Home" },
                                    { "Action", "TimeoutRedirect" }}  );
于 2015-01-23T09:00:32.373 回答
0

我有一个旧的 Web 表单应用程序,我必须将其转换为 MVC 5,其中一个要求是支持可能的 {old_form}.aspx 链接。在 Global.asax Application_BeginRequest 中,我设置了一个 switch 语句来处理旧页面以重定向到新页面,并避免可能不希望的循环到请求的原始 URL 中的“.aspx”的主/默认路由检查。

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        OldPageToNewPageRoutes();
    }

    /// <summary>
    /// Provide redirects to new view in case someone has outdated link to .aspx pages
    /// </summary>
    private void OldPageToNewPageRoutes()
    {
        // Ignore if not Web Form:
        if (!Request.RawUrl.ToLower().Contains(".aspx"))
            return;

        // Clean up any ending slasshes to get to the old web forms file name in switch's last index of "/":
        var removeTrailingSlash = VirtualPathUtility.RemoveTrailingSlash(Request.RawUrl);
        var sFullPath = !string.IsNullOrEmpty(removeTrailingSlash)
            ? removeTrailingSlash.ToLower()
            : Request.RawUrl.ToLower();
        var sSlashPath = sFullPath;

        switch (sSlashPath.Split(Convert.ToChar("/")).Last().ToLower())
        {
            case "default.aspx":
                Response.RedirectToRoute(
                    new RouteValueDictionary
                    {
                        {"Controller", "Home"},
                        {"Action", "Index"}
                    });
                break;
            default:
                // Redirect to 404:
                Response.RedirectToRoute(
                    new RouteValueDictionary
                    {
                        {"Controller", "Error"},
                        {"Action", "NotFound"}
                    });
                break;

        }
    }
于 2016-05-23T15:53:03.667 回答
0

就我而言,我不喜欢使用 Web.config。然后我在 Global.asax 文件中创建了上面的代码:

protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();

        //Not Found (When user digit unexisting url)
        if(ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
        {
            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "NotFound");

            IController controller = new ErrorController();
            RequestContext requestContext = new RequestContext(contextWrapper, routeData);
            controller.Execute(requestContext);
            Response.End();
        }
        else //Unhandled Errors from aplication
        {
            ErrorLogService.LogError(ex);
            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");

            IController controller = new ErrorController();
            RequestContext requestContext = new RequestContext(contextWrapper, routeData);
            controller.Execute(requestContext);
            Response.End();
        }
    }

那就是我的 ErrorController.cs

public class ErrorController : Controller
{
    // GET: Error
    public ViewResult Index()
    {
        Response.StatusCode = 500;
        Exception ex = Server.GetLastError();
        return View("~/Views/Shared/SAAS/Error.cshtml", ex);
    }

    public ViewResult NotFound()
    {
        Response.StatusCode = 404;
        return View("~/Views/Shared/SAAS/NotFound.cshtml");
    }
}

这就是我的基于 mason 类的 ErrorLogService.cs

//common service to be used for logging errors
public static class ErrorLogService
{
    public static void LogError(Exception ex)
    {
        //Do what you want here, save log in database, send email to police station
    }
}
于 2019-11-12T12:19:46.247 回答
-4

你可以试试这个:

上下文.响应.重定向(); 

不确定。

于 2011-08-16T10:45:57.040 回答