Redirect from a ViewComponent

Hi All,

Not sure if this is possible, but I am trying to perform a redirection from within a View Component. From Google searches, I understand it would be better to do the redirect from the razor page, however in this case, it is not as straightforward.

I can perform the redirect by injecting IHttpContextAccessor, in the View Component, and calling

_httpContextAccessor.HttpContext.Response.Redirect(url);

to redirect to the required page. However when I do this, Umbraco appears to process the View Component cshtml file anyway, and since a model is not being passed to the View, I am having to wrap all Razor code which accesses the Model in an if statement which checks the Model is not null.

Is there a better way to do this?

Thanks

Kap.


This is a companion discussion topic for the original entry at https://our.umbraco.com/forum/114904-redirect-from-a-viewcomponent

The way I solved this was to have a different view to point the ViewComponent to.

if(doRedirect) {
    View("RedirectView", redirectUrl);
}
else {
   View(model);
}

Then in my RedirectView.cshtml:

@using ContentModels = Umbraco.Cms.Web.Common.PublishedModels;

@model string

@{
    Context.Response.Redirect(Model);
}

Works perfectly when exporting a csv file.