Asp.net mvc 重定向到global.asax中应用程序_BeginRequest的操作

Asp.net mvc 重定向到global.asax中应用程序_BeginRequest的操作,asp.net-mvc,asp.net-mvc-4,asp.net-mvc-3,asp.net-mvc-5,asp.net-mvc-2-validation,Asp.net Mvc,Asp.net Mvc 4,Asp.net Mvc 3,Asp.net Mvc 5,Asp.net Mvc 2 Validation,在我的web应用程序中,我正在验证glabal.asax中的url。我想验证url,如果需要,需要重定向到操作。我正在使用应用程序_BeginRequest捕获请求事件 protected void Application_BeginRequest(object sender, EventArgs e) { // If the product is not registered then // redirect the user to product

在我的web应用程序中,我正在验证glabal.asax中的url。我想验证url,如果需要,需要重定向到操作。我正在使用应用程序_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,并在需要时重定向到某个操作

您可以尝试以下方法:

Response.Redirect();

不确定。

试试这个:

HttpContext.Current.Response.Redirect("...");

使用以下代码进行重定向

   Response.RedirectToRoute("Default");

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

以上所有操作都不起作用,您将处于执行方法
应用程序\u BeginRequest
的循环中

你需要使用

HttpContext.Current.RewritePath("Home/About");
我是这样做的:

        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。另一种方法是使用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"));
    }
}

我有一个旧的web表单应用程序,我必须转换为MVC5,其中一个要求是支持可能的{old_form}.aspx链接。在Global.asax应用程序_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;

        }
    }
受保护的无效应用程序\u BeginRequest(对象发送方,事件参数e)
{
OldPageToNewPageRoutes();
}
/// 
///提供指向新视图的重定向,以防有人有指向.aspx页面的过期链接
/// 
私有void OldPageToNewPageRoutes()
{
//如果不是Web表单,则忽略:
如果(!Request.RawUrl.ToLower()包含(“.aspx”))
返回;
//清除所有结尾斜杠,以获取交换机最后一个索引“/”中的旧web表单文件名:
var removeTrailingSlash=virtualPath实用性.removeTrailingSlash(Request.RawUrl);
var sFullPath=!string.IsNullOrEmpty(removetRailingFlash)
?拆下导轨间隙ToLower()
:Request.RawUrl.ToLower();
var sSlashPath=sFullPath;
开关(sSlashPath.Split(Convert.ToChar(“/”).Last().ToLower())
{
案例“default.aspx”:
Response.RedirectToRoute(
新RouteValueDictionary
{
{“控制器”,“主”},
{“操作”,“索引”}
});
打破
违约:
//重定向到404:
Response.RedirectToRoute(
新RouteValueDictionary
{
{“控制器”,“错误”},
{“操作”,“未找到”}
});
打破
}
}

就我而言,我不喜欢使用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
    }
}

可能的重复将创建一个loop@Null指针,请接受其他有效答案之一?如果在应用程序_beginRequest函数中使用,则会导致重定向循环发生。这将导致另一个请求;这将导致另一个请求。这会导致另一个请求。这就创造了另一个。直到它完全出错。这会导致另一个请求。这反过来又造成了另一个,。这是另一个原因。等等,当您在应用程序开始请求函数中时。@RichardBarker此代码不在应用程序开始请求中!!!!我把它放在应用程序\u PostAuthenticateRequest中,并在cas中的catch块中执行了一次测试。发生错误,我深表歉意。这个问题开始引起人们的兴趣。我可以建议您更新您的答案以显示这一点并解释您为什么这么做吗?这样会更好一些,但我根据您的更新创建了一个简短完整的代码示例。这将有助于未来的堆垛机,使其更容易理解和利用。我相信这是解决OP中描述的问题的最佳解决方案-它将避免循环问题,但首先需要再次检查登录操作的当前请求。我喜欢这一点,因为它从帮助器生成MVC路由,并将固有地处理路由的更改。我从不喜欢将MVC路由硬编码为字符串!
//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
    }
}