Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like "RewriteToAction"?

Knowing RedirectToAction, I was looking for something similar to keep the URL stable for the user and still pass responsibility from one action to another.

Since I found zero Google results on this topic, I might as well completely try to solve an XY problem.

Still, I'll try to explain why I believe there might be a need for this.

Scenario:

public ActionResult A(int id)
{
    var uniqueID = CalculateUniqueFromId(id);

    // This compiles.
    return RedirectToAction("B", new { uniqueID });

    // This does not compile.
    return RewriteToAction("B", new { uniqueID });
}

public ActionResult B(Guid uniqueID)
{
    var model = DoCreateModelForUnique(uniqueID);
    return View("B", model);
}

In above code, action A calculates a guid from an integer and passes it to another action.

Workaround:

I could change the above code to something like this:

public ActionResult A(int id)
{
    var uniqueID = CalculateUniqueFromId(id);
    var model = DoCreateModelForUnique(uniqueID);

    return View("B", model);
}

public ActionResult B(Guid uniqueID)
{
    var model = DoCreateModelForUnique(uniqueID);
    return View("B", model);
}

This would work as expected.

Still, in more complex scenarios, I would love to have a "server-side redirect" (aka rewrite) to use every now and then.

Alternative workaround:

I also could use HttpContext.RewritePath, e.g. inside Global.asax's Application_BeginRequest to do a rewrite.

This feels to me "out of the MVC context", even though it works as expected.

My question:

Is there an elegant, MVC-integrated way of doing something like RewriteToAction?

Update 1:

Luke commented a promising link:

How to simulate Server.Transfer in ASP.NET MVC?

I'll try to investigate, whether this fits my needs.

like image 476
Uwe Keim Avatar asked Apr 18 '17 08:04

Uwe Keim


1 Answers

How about

public ActionResult A(int id)
{
    var uniqueID = CalculateUniqueFromId(id);

    return B(uniqueID);
}

public ActionResult B(Guid uniqueID)
{
    var model = DoCreateModelForUnique(uniqueID);
    return View("B", model);
}

?

like image 173
NP3 Avatar answered Sep 30 '22 11:09

NP3