How to use Url.Action() in a class file?
Asked Answered
F

7

28

How can I use Url.Action() in a class file of MVC project?

Like:

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"));
            }
        }
    }
}
Fiona answered 1/1, 2014 at 13:44 Comment(0)
D
47

You will need to manually create the UrlHelper class and pass the appropriate RequestContext. It could be done with something like:

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

However, you are trying to achieve redirection based on authentication. I suggest you look at implementing a custom AuthorizeAttribute filter to achieve this kind of behavior to be more in line with the framework

Devaney answered 1/1, 2014 at 13:54 Comment(3)
thanks mate, again you saved my life :) or time(?) :} love youWeird
Should be Action("<Action>", "<Controller>") instead of Action("<Controller>", "<Action>") as aboveHouseline
@Houseline That is correct. Semantic aside, the answer do not attempt to decrypt whether Ercin has inverted the values and uses the same as provided in the original question.Devaney
F
6

Pass the RequestContext to your custom class from the controller. I would add a Constructor to your custom class to handle this.

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

You need to import System.Web.Mvc namespace to this class to use the UrlHelper class.

Now in your controller, create an object of MyCustomClass and pass the controller context in the constructor,

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();
Fantan answered 1/1, 2014 at 13:55 Comment(1)
working good thanks a lot fully object oriented but Simon's solution simple to use. I marked as bookmark thanks a lot! loves...Weird
O
2

For those arriving late to this post, using .Net Core and .Net 5.0, You should try this;

private readonly IUrlHelperFactory _urlHelperFactory;
private readonly IActionContextAccessor _actionContextAccessor;

 public EmailSenderService(IUrlHelperFactory urlHelperFactory,
            IActionContextAccessor actionContextAccessor)
        {
            _urlHelperFactory = urlHelperFactory;
            _actionContextAccessor = actionContextAccessor;
        }

 private string GenerateUrl(string action, string controller, object routeValues = null)
        {
            var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);
            return urlHelper.Action(action, controller, routeValues, _actionContextAccessor.ActionContext.HttpContext.Request.Scheme);
        }
Overshoe answered 9/12, 2020 at 7:56 Comment(2)
I asked that question 6+ years ago. and for legacy framework ofc. but thx for your contr.Weird
I just didn't answer for you. If you pay attention I've shared how to do it for .Net Core and .Net 5.0.Overshoe
L
1

@Simon Belanger's answer is perfectly working, but UrlHelper.Action() generates relative URLs and in my case i need the fully qualified absolute URL. So what i need to do is - i have to use one of the overload provided by UrlHelper.Action() method.

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

So let say if your application hosted on "https://myexamplesite.com" then above code will give you full url like this - "https://myexamplesite.com/Home/Index". Hope this answer will help those readers who will come across this link.

Liana answered 15/5, 2019 at 12:39 Comment(0)
R
1

You simply need to pass Url property from your controller to your class file,

string CreateRoutingUrl(IUrlHelper url)
{
    return url.Action("Action", "Controller");
}

and on your controller :

MyClass.CreateRoutingUrl(Url);
Runway answered 20/3, 2021 at 10:36 Comment(0)
S
0

I tried to use @simion's answer and I was getting an invalid type in the constructor for UrlHelper. "cannot convert from System.Web.Routing.RequestContext to System.Net.Http.HttpRequestMessage"

So I used this

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

worked out for me.

Specify answered 11/9, 2018 at 20:33 Comment(0)
I
0

You can also use this

return RedirectToAction("Index", "MainPage");
Ioannina answered 14/12, 2020 at 3:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.