ASP.NET MVC のモデルでいくつかの URL を生成する必要があります。ルートを使用して URL を生成する UrlHelper.Action() のようなものを呼び出したいと思います。ホスト名、スキームなどの通常の空白を埋めてもかまいません。
そのために呼び出すことができる方法はありますか?UrlHelper を構築する方法はありますか?
ASP.NET MVC のモデルでいくつかの URL を生成する必要があります。ルートを使用して URL を生成する UrlHelper.Action() のようなものを呼び出したいと思います。ホスト名、スキームなどの通常の空白を埋めてもかまいません。
そのために呼び出すことができる方法はありますか?UrlHelper を構築する方法はありますか?
役立つヒント、どのASP.NETアプリケーションでも、現在のHttpContextの参照を取得できます
HttpContext.Current
これはSystem.Webから派生しています。したがって、以下はASP.NETMVCアプリケーションのどこでも機能します。
UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
url.Action("ContactUs"); // Will output the proper link according to routing info
例:
public class MyModel
{
public int ID { get; private set; }
public string Link
{
get
{
UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
return url.Action("ViewAction", "MyModelController", new { id = this.ID });
}
}
public MyModel(int id)
{
this.ID = id;
}
}
作成されたMyModelオブジェクトのプロパティを呼び出すとLink、Global.asaxのルーティングに基づいてモデルを表示するための有効なURLが返されます。
私はオマールの答えが好きですが、それは私にとってはうまくいきません。記録のために、これは私が現在使用しているソリューションです:
var httpContext = HttpContext.Current;
if (httpContext == null) {
var request = new HttpRequest("/", "http://example.com", "");
var response = new HttpResponse(new StringWriter());
httpContext = new HttpContext(request, response);
}
var httpContextBase = new HttpContextWrapper(httpContext);
var routeData = new RouteData();
var requestContext = new RequestContext(httpContextBase, routeData);
return new UrlHelper(requestContext);
UrlHelper は、次のように Controller アクション内から構築できます。
var url = new UrlHelper(this.ControllerContext.RequestContext);
url.Action(...);
コントローラーの外部では、RouteTable.Routes の RouteData から RequestContext を作成することにより、UrlHelper を構築できます。
HttpContextWrapper httpContextWrapper = new HttpContextWrapper(System.Web.HttpContext.Current);
UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper)));
(ブライアンの回答に基づいて、マイナーなコード修正が追加されました。)
はい、インスタンス化できます。次のようなことができます:
var ctx = new HttpContextWrapper(HttpContext.Current);
UrlHelper helper = new UrlHelper(
new RequestContext(ctx,
RouteTable.Routes.GetRouteData(ctx));
RouteTable.Routesは静的プロパティなので、問題ありません。へのHttpContextBase参照を取得HttpContextWrapperしHttpContext、それをHttpContext配信します。
ページ内(コントローラーの外側)から同様のことをしようとしていました。
UrlHelper では、Pablos の回答ほど簡単に作成することはできませんでしたが、同じことを効果的に行うための古いトリックを思い出しました。
string ResolveUrl(string pathWithTilde)
あなたが探しているのはこれだと思います:
Url.Action("ActionName", "ControllerName");