web-dev-qa-db-ja.com

クラスファイルで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"));
            }
        }
    }
}
20

UrlHelper クラスを手動で作成し、適切なRequestContextを渡す必要があります。それは次のようなもので行うことができます:

var requestContext = HttpContext.Current.Request.RequestContext;
new UrlHelper(requestContext).Action("Index", "MainPage");

ただし、認証に基づいてリダイレクトを実現しようとしています。カスタム AuthorizeAttribute フィルターの実装を見て、この種の動作を実現して、フレームワークにより一致するようにすることをお勧めします

34
Simon Belanger

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;
    }
}

インポートする必要があります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();
5
Shyju

@Simon Belangerの答えは完全に機能していますが、UrlHelper.Action()は相対URLを生成します。私の場合、完全修飾絶対URLが必要です。だから私がする必要があるのは-私は rlHelper.Action() メソッドによって提供されるオーバーロードの1つを使わなければなりません。

var requestContext = HttpContext.Current.Request.RequestContext;
string link = new UrlHelper(requestContext).Action("Index", "Home", null, HttpContext.Current.Request.Url.Scheme);

したがって、アプリケーションが " https://myexamplesite.com "でホストされている場合、上記のコードは次のような完全なURLを提供します-" https://myexamplesite.com/Home/インデックス "。この回答がこのリンクに出くわす読者に役立つことを願っています。

1
Krishnraj Rana

@simionの回答を使用しようとしましたが、UrlHelperのコンストラクターで無効な型を取得していました。 「System.Web.Routing.RequestContextからSystem.Net.Http.HttpRequestMessageに変換できません」

だから私はこれを使いました

var urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext); string url = urlHelper.Action("MainPage", "Index");

私のために働いた。

0
domshyra