MVC 5 UrlHelper without HTTPContext? - asp.net-mvc

I decorate my MVC 5 actions with route attributes:
[Route("this-test")]
public ActionResult ThisTest()
and with a HTTPContext I can access the route name like so:
UrlHelper helper = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
string actionUrl = helper.Action("ThisTest", "Home");
However I'm using Hangfire chron jobs to fire off some emails. Since I don't have a HTTPContext I cannot use the code above to obtain my route of "home/this-test/".
Is this possible to achieve? Thank you.

Look at this topic:
Passing site URL to hangfire recurrent jobs.
Relying on the answer there, there's no way to receive the domain inside a Hangfire job. It seems like passing the URL of your site as a parameter to a job is the most clear solution.

Related

Accessing route URLs in the controller in ASP.Net MVC

ASP.Net MVC has some really nice features for making sure that you have the correct URL for the route you want. So I can use the HtmlHelper class you get the correct URL for my views:-
#Html.RouteLink("Link Text", new {controller = "articles", action = "tag"})
Now this is great. However, I find myself in the situation that I want to know the URL but I am not writing it into a view. So my question is what is the best way to get this information in the controller? I have read various posts that show you how to sneakily create an instance of HtmlHelper but there must be a more straightforward way of doing this.
Thanks.
You can try the UrlHelper.RouteUrl. UrlHelper is accessible via the Url property on controller.
Controller has access to all information about the request, so Request object is where you can find the Url
Request.Url.ToString()

ASP.NET MVC catch URL parameter in Controller

I've defined such a controller ViewProfile.
I want to use it for the next syntax to access public user info in my project.
/ViewProfile/Sammy
/ViewProfile/Billy
etc...
But I don't know how to handle the 2-nd parameter in URL.
I've tried to use:
[HttpGet]
public ActionResult Index(string query)
{
...
return View();
}
But in the debugger, string query is always empty.
I have read about routines mapping, but really don't understand how would it help me with the determination of id or other parameters.
I read in ASP.NET MVC Book that to get the parameter directly in the controller action just name it as ID.
ASP.NET MVC lets you easily do this without having to confi gure
anything extra. ASP .NET MVC’s default routing convention is to treat
the segment of a URL after the action method name as a parameter named
ID. If your action method has a parameter named ID, then ASP.NET MVC
will automatically pass the URL segment to you as a parameter.
I just tried a sample app and it worked fine for me. The string i entered in the URL did get passed on to the ID parameter in the action.
Also what i noticed is that you should provide your URL as viewprofile/index/1 or
viewprofile/index/somestring.
YOu seem to be skipping the action part.

MVC custom routing function

This is a more specific version of another of my questions: Restful MVC Web Api Inheritance, I hope an answer to this will help me answer that.
Im using ASP.NET web api,
I want to be able to route something like this: [{object}/{id}]/{controller}/{id}.
so i want an array of objects with optional /{id} ending with the 'api endpoint'.
I want to be able to route these:
/houses
/houses/3
suburbs/3/houses
council/5/suburbs/houses
city/8/council/suburbs/houses
ETC
TO
get(List<restRoute>parents, int id){
...
}
restRoute would be an object with a string for the object and an optional int (or guid etc) for the id
Does anyone know where i can start?
I don't want to route every single one individually.
I had also such problems with routing from the box in ASP.NET MVC. Its good way to be used as common routing, but is not so flexible for custom routs.
In WCF Web Api (ASP.NET web api in CTP version) was used attribute based routing.
I think its more flexible, but as negative point - each method should have routing attribute.
Take a look at this blog post:
http://www.strathweb.com/2012/05/attribute-based-routing-in-asp-net-web-api/
It describes how to implement attribute based routing using ASP.NET Web Api. Because such approach is more flexible for routes you can map to methods, it can be helpful for you.
You could use the {*anything} Variable Segmented URL pattern in your route and handle the splitting up and figuring out of what part of the url corresponds to what bit of data in your method:
Global.asax:
routes.MapRoute(
"Special", // name
"{*allthethings}", // parameters
new { controller = "Special", action = "Sauce" } // defaults
);
SpecialController:
public ActionResult Sauce()
{
string data = RouteData.Values["allthethings"].ToString();
string[] items = data.Split('/');
foreach (string item in items)
{
// do whatever you need to figure out which is what!
}
return View();
}
If you wanted to be a bit cleverer about it you could create your own custom RouteHandler to do the splitting. Something like David Ebb's PK routehandler would probably do the trick, with some customisation to fit your requirements in the processing of the route. You could use this to split up the "allthethings" parameter and turn it into your List<RestRoute> format before passing the request on to the Controller

How do I set the protocol when using RedirectToAction?

The action I target needs https. I already have a filter in place that redirects to https if a request comes in via http, but I would prefer to send the request via https right from the start.
EDIT
There was an answer from Darin (updated now to something else ) where he asked why I call this first action by http anyway. He had a good point there and I just updated a couple of links. This was the easiest and securest way to fix my problem.
Once I find the time to evaluate çağdaş answer I will use this as the correct answer, because I guess thats of interest for some other people (...including me in the future)
I don't know if you must use RedirectToAction but with a UrlHelper and the controller's Redirect method you can do this :
public ActionResult SomeAction() {
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
return Redirect(u.Action("actionName", "controllerName", null, "https"));
}
ASP.NET MVC 3 includes the RequireHttpsAttribute which may be of assistance.

ASP.NET MVC: How to create a usable UrlHelper instance?

I am using quartz.net to schedule regular events within asp.net mvc application.
The scheduled job should call a service layer script that requires a UrlHelper instance (for creating Urls based on correct routes (via urlHelper.Action(..)) contained in emails that will be sent by the service).
I do not want to hardcode the links into the emails - they should be resolved using the urlhelper.
The job:
public class EvaluateRequestsJob : Quartz.IJob
{
public void Execute(JobExecutionContext context)
{
// where to get a usable urlHelper instance?
ServiceFactory.GetRequestService(urlHelper).RunEvaluation();
}
}
Please note that this is not run within the MVC pipeline. There is no current request being served, the code is run by the Quartz scheduler at defined times.
How do I get a UrlHelper instance usable on the indicated place?
If it is not possible to construct a UrlHelper, the other option I see is to make the job "self-call" a controller action by doing a HTTP request - while executing the action I will of course have a UrlHelper instance available - but this seems a little bit hacky to me.
How about just creating a new HttpContext for the UrlHelpler as in this answer:
Edit: Sorry I totally mis-read the question I guess.
It sounds like your scheduler (which I have no idea how it works) is a seperate process and you want the UrlHelper to help generate valid URLs in your MVC app?
You could try writing a handler in your MVC app that will be running under your applications context that will build the URL for you and return it. You could then call the handler from your scheduler to get any URL you need based on the params you pass in. This way your scheduler just needs to know about where the query URL of your MVC app is and then can ask it to do the Url mapping for you.
Hope this is a bit better of an answer. If I am totally off let me know... was going to delete my response but thought I would give it one more shot.
Remember to specify the protocol parameter when using UrlHelper.Action method, this will generate absolute urls. Example:
url.Action("Action", "Controller", null, "http")
or
url.Action("Action", "Controller", null, request.Url.Scheme)
You need a RequestContext to create a UrlHelper. In one of my HtmlHelper extension methods, I do it like this:
public static string ScriptUrl(this HtmlHelper html, string script)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
...
}
How you get the RequestContext is dependent on your application.

Resources