patterncsharpMinor
Update URL with new parameter value in controller action
Viewed 0 times
updatenewwithvaluecontrolleractionurlparameter
Problem
I have an action that takes an id as a parameter and gets the corresponding item with the help of a web service. The web service's method that returns the item will either return the item with the requested id, or will create a new item (new version of the item) with a new id. So, in the case that a new item is created, the response's header should be updated with the new item's id.
Here's what the route corresponding to that controller action looks like:
So when an user requests the item with the id
MyArea/MyController/MyAction/12
Let's say the web service creates a new version of the above item, and its id is
I was wondering if there was a better way to reconstruct the URL with the updated id. I also tried reconstructing the URL with the
Here's what the route corresponding to that controller action looks like:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"default",
"MyArea/{Controller}/{action}/{id}",
new { controller = "MyController", action = "Index", id = UrlParameter.Optional }
);
}So when an user requests the item with the id
12, the request's path will look like:MyArea/MyController/MyAction/12
Let's say the web service creates a new version of the above item, and its id is
13, I'd like to update the URL accordingly. Here's what my action looks like:[HttpGet]
public async Task EditItem(int id)
{
try
{
Item myItem = await _myWS.Channel.GetItemAsync(id);
// If a new version has been created, change the url in order to show the new id
if (myItem.Id != id)
{
Response.StatusCode = 301;
string newUrl = Request.Path;
int lastSlashIndex = newUrl.LastIndexOf("/");
if (lastSlashIndex > 0)
newUrl = newUrl.Substring(0, lastSlashIndex + 1) + myItem.Id;
Response.AddHeader("Location", newUrl);
Response.End();
}
return View("MyView", (ItemViewModel)myItem);
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}I was wondering if there was a better way to reconstruct the URL with the updated id. I also tried reconstructing the URL with the
Request.RequestContext.RouteData.Values, but I thought the code was less readable and more complicateSolution
I believe you want
RedirectToActionPermanent:if (myItem.Id != id)
{
return RedirectToActionPermanent("EditItem", new { id = id })
}Code Snippets
if (myItem.Id != id)
{
return RedirectToActionPermanent("EditItem", new { id = id })
}Context
StackExchange Code Review Q#158307, answer score: 4
Revisions (0)
No revisions yet.