如何在类文件中使用Url.Action()?

Erç*_*ğlu 19 c# asp.net-mvc url.action

如何在MVC项目的类文件中使用Url.Action()?

喜欢:

namespace _3harf
{
    public class myFunction
    {
        public static void CheckUserAdminPanelPermissionToAccess()
        {
            if (ReferenceEquals(HttpContext.Current.Session["Loged"], "true") &&
                myFunction.GetPermission.AdminPermissionToLoginAdminPanel(
                    Convert.ToInt32(HttpContext.Current.Session["UID"])))
            {
                HttpContext.Current.Response.Redirect(Url.Action("MainPage", "Index"));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*ger 35

您需要手动创建UrlHelper类并传递适当的类RequestContext.它可以通过以下方式完成:

var requestContext = HttpContext.Current.Request.RequestContext;
new UrlHelper(requestContext).Action("Index", "MainPage");
Run Code Online (Sandbox Code Playgroud)

但是,您正在尝试基于身份验证实现重定向.我建议你看看实现一个自定义AuthorizeAttribute过滤器来实现这种行为更符合框架

  • 应该是Action("<Action>","<Controller>")而不是Action("<Controller>","<Action>"),如上所示 (6认同)

Shy*_*yju 5

RequestContext从控制器将传递给您的自定义类。我会在您的自定义类中添加一个构造函数来处理此问题。

using System.Web.Mvc;
public class MyCustomClass
{
    private UrlHelper _urlHelper;
    public MyCustomClass(UrlHelper urlHelper)
    {
        _urlHelper = urlHelper;
    }
    public string GetThatURL()
    {         
      string url=_urlHelper.Action("Index", "Invoices"); 
      //do something with url or return it
      return url;
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要将System.Web.Mvc名称空间导入到此类中才能使用UrlHelper类。

现在,在您的控制器中,创建一个对象MyCustomClass并在构造函数中传递控制器上下文,

UrlHelper uHelp = new UrlHelper(this.ControllerContext.RequestContext);
var myCustom= new MyCustomClass(uHelp );    
//Now call the method to get the Paging markup.
string thatUrl= myCustom.GetThatURL();
Run Code Online (Sandbox Code Playgroud)