How to handle an exception in .NET Core Razor pages PageModel and stay on same view?
I am trying to figure out how to wire up exception handling in an ASP.NET Core Razor pages site to allow the user to stay on the same page when an exception occurs with a friendly error message.
Once the user submits the form on the Edit view, call the back end middle-tier to persist the data if they have the proper permissions. If they don't have proper permissions, a custom validation exception is thrown from the middle-tier.
private readonly IToolsService m_oToolsService;
public EditModel(IToolsService toolsService)
{
m_oToolsService = oToolsService;
}
public async Task<IActionResult> OnGetAsync()
{
var vm = olsService.GetData():
// Wire up UI with the ViewModel
return Page();
}
public async Task<IActionResult> OnPostEditAsync(ViewModel vm)
{
if (false == ModelState.IsValid)
{
return Page();
}
m_oToolsService.SaveData(vm);
}
If the call to "m_oToolsService.SaveData(vm);" fails, I'd like to keep the user on the same page with a friendly error message (and with the form data that they tried to post).
I could wrap the OnPost/OnGet ActionMethods with try/catch blocks, however, that gets redundant in all of the PageModels and bloats the code.
I have tried adding custom exception handling Middleware, and while that will catch the custom error, it redirects the user to an error page.
I have also added a custom exception filter similar to the example below but that isn't keeping the user on the page either.
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public CustomExceptionFilterAttribute(IHostingEnvironment hostingEnvironment, ITempDataDictionaryFactory tempDataDictionaryFactory, IModelMetadataProvider modelMetadataProvider)
{
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public override void OnException(ExceptionContext context)
{
if (!_hostingEnvironment.IsDevelopment())
{
// do nothing
return;
}
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
var result = new ViewResult
{
ViewName = "/Edit",
};
context.ExceptionHandled = true; // mark exception as handled
HttpResponse response = context.HttpContext.Response;
context.Result = result;
}
No matter what I research, everything seems to point back to using the .NET Core Middleware to redirect to a specific error page. Does anyone have any ideas on how to handle exceptions but keep the user on the same view?
c# razor asp.net-core exception-handling razor-pages
add a comment |
I am trying to figure out how to wire up exception handling in an ASP.NET Core Razor pages site to allow the user to stay on the same page when an exception occurs with a friendly error message.
Once the user submits the form on the Edit view, call the back end middle-tier to persist the data if they have the proper permissions. If they don't have proper permissions, a custom validation exception is thrown from the middle-tier.
private readonly IToolsService m_oToolsService;
public EditModel(IToolsService toolsService)
{
m_oToolsService = oToolsService;
}
public async Task<IActionResult> OnGetAsync()
{
var vm = olsService.GetData():
// Wire up UI with the ViewModel
return Page();
}
public async Task<IActionResult> OnPostEditAsync(ViewModel vm)
{
if (false == ModelState.IsValid)
{
return Page();
}
m_oToolsService.SaveData(vm);
}
If the call to "m_oToolsService.SaveData(vm);" fails, I'd like to keep the user on the same page with a friendly error message (and with the form data that they tried to post).
I could wrap the OnPost/OnGet ActionMethods with try/catch blocks, however, that gets redundant in all of the PageModels and bloats the code.
I have tried adding custom exception handling Middleware, and while that will catch the custom error, it redirects the user to an error page.
I have also added a custom exception filter similar to the example below but that isn't keeping the user on the page either.
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public CustomExceptionFilterAttribute(IHostingEnvironment hostingEnvironment, ITempDataDictionaryFactory tempDataDictionaryFactory, IModelMetadataProvider modelMetadataProvider)
{
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public override void OnException(ExceptionContext context)
{
if (!_hostingEnvironment.IsDevelopment())
{
// do nothing
return;
}
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
var result = new ViewResult
{
ViewName = "/Edit",
};
context.ExceptionHandled = true; // mark exception as handled
HttpResponse response = context.HttpContext.Response;
context.Result = result;
}
No matter what I research, everything seems to point back to using the .NET Core Middleware to redirect to a specific error page. Does anyone have any ideas on how to handle exceptions but keep the user on the same view?
c# razor asp.net-core exception-handling razor-pages
Add a property to your Model that holds the exception message and model bind it to your view, place at try-catch inside your Action and if an exception occurs, set the property of your model with the exception details and return the model to the View without doing a RedirectToAction
– Ryan Wilson
Jan 19 at 20:31
Yes, I could add a try-catch block inside each action that calls the middle-tier code and set a property and the model state to invalid and redisplay the view. To be more specific with my question, I'm wondering if there is a better, more global approach to do similar functionality and not have a try-catch block in each Action method?
– LilCrabner
Jan 19 at 20:42
If you can decipher what action was called and from what controller when the exception occurs, couldn't you just redirect to that controller/action with the model with an updated model property of the exception instead of directing to the error page?
– Ryan Wilson
Jan 19 at 20:46
add a comment |
I am trying to figure out how to wire up exception handling in an ASP.NET Core Razor pages site to allow the user to stay on the same page when an exception occurs with a friendly error message.
Once the user submits the form on the Edit view, call the back end middle-tier to persist the data if they have the proper permissions. If they don't have proper permissions, a custom validation exception is thrown from the middle-tier.
private readonly IToolsService m_oToolsService;
public EditModel(IToolsService toolsService)
{
m_oToolsService = oToolsService;
}
public async Task<IActionResult> OnGetAsync()
{
var vm = olsService.GetData():
// Wire up UI with the ViewModel
return Page();
}
public async Task<IActionResult> OnPostEditAsync(ViewModel vm)
{
if (false == ModelState.IsValid)
{
return Page();
}
m_oToolsService.SaveData(vm);
}
If the call to "m_oToolsService.SaveData(vm);" fails, I'd like to keep the user on the same page with a friendly error message (and with the form data that they tried to post).
I could wrap the OnPost/OnGet ActionMethods with try/catch blocks, however, that gets redundant in all of the PageModels and bloats the code.
I have tried adding custom exception handling Middleware, and while that will catch the custom error, it redirects the user to an error page.
I have also added a custom exception filter similar to the example below but that isn't keeping the user on the page either.
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public CustomExceptionFilterAttribute(IHostingEnvironment hostingEnvironment, ITempDataDictionaryFactory tempDataDictionaryFactory, IModelMetadataProvider modelMetadataProvider)
{
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public override void OnException(ExceptionContext context)
{
if (!_hostingEnvironment.IsDevelopment())
{
// do nothing
return;
}
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
var result = new ViewResult
{
ViewName = "/Edit",
};
context.ExceptionHandled = true; // mark exception as handled
HttpResponse response = context.HttpContext.Response;
context.Result = result;
}
No matter what I research, everything seems to point back to using the .NET Core Middleware to redirect to a specific error page. Does anyone have any ideas on how to handle exceptions but keep the user on the same view?
c# razor asp.net-core exception-handling razor-pages
I am trying to figure out how to wire up exception handling in an ASP.NET Core Razor pages site to allow the user to stay on the same page when an exception occurs with a friendly error message.
Once the user submits the form on the Edit view, call the back end middle-tier to persist the data if they have the proper permissions. If they don't have proper permissions, a custom validation exception is thrown from the middle-tier.
private readonly IToolsService m_oToolsService;
public EditModel(IToolsService toolsService)
{
m_oToolsService = oToolsService;
}
public async Task<IActionResult> OnGetAsync()
{
var vm = olsService.GetData():
// Wire up UI with the ViewModel
return Page();
}
public async Task<IActionResult> OnPostEditAsync(ViewModel vm)
{
if (false == ModelState.IsValid)
{
return Page();
}
m_oToolsService.SaveData(vm);
}
If the call to "m_oToolsService.SaveData(vm);" fails, I'd like to keep the user on the same page with a friendly error message (and with the form data that they tried to post).
I could wrap the OnPost/OnGet ActionMethods with try/catch blocks, however, that gets redundant in all of the PageModels and bloats the code.
I have tried adding custom exception handling Middleware, and while that will catch the custom error, it redirects the user to an error page.
I have also added a custom exception filter similar to the example below but that isn't keeping the user on the page either.
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;
private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
public CustomExceptionFilterAttribute(IHostingEnvironment hostingEnvironment, ITempDataDictionaryFactory tempDataDictionaryFactory, IModelMetadataProvider modelMetadataProvider)
{
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
_tempDataDictionaryFactory = tempDataDictionaryFactory;
}
public override void OnException(ExceptionContext context)
{
if (!_hostingEnvironment.IsDevelopment())
{
// do nothing
return;
}
var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
var result = new ViewResult
{
ViewName = "/Edit",
};
context.ExceptionHandled = true; // mark exception as handled
HttpResponse response = context.HttpContext.Response;
context.Result = result;
}
No matter what I research, everything seems to point back to using the .NET Core Middleware to redirect to a specific error page. Does anyone have any ideas on how to handle exceptions but keep the user on the same view?
c# razor asp.net-core exception-handling razor-pages
c# razor asp.net-core exception-handling razor-pages
asked Jan 19 at 20:28
LilCrabnerLilCrabner
11
11
Add a property to your Model that holds the exception message and model bind it to your view, place at try-catch inside your Action and if an exception occurs, set the property of your model with the exception details and return the model to the View without doing a RedirectToAction
– Ryan Wilson
Jan 19 at 20:31
Yes, I could add a try-catch block inside each action that calls the middle-tier code and set a property and the model state to invalid and redisplay the view. To be more specific with my question, I'm wondering if there is a better, more global approach to do similar functionality and not have a try-catch block in each Action method?
– LilCrabner
Jan 19 at 20:42
If you can decipher what action was called and from what controller when the exception occurs, couldn't you just redirect to that controller/action with the model with an updated model property of the exception instead of directing to the error page?
– Ryan Wilson
Jan 19 at 20:46
add a comment |
Add a property to your Model that holds the exception message and model bind it to your view, place at try-catch inside your Action and if an exception occurs, set the property of your model with the exception details and return the model to the View without doing a RedirectToAction
– Ryan Wilson
Jan 19 at 20:31
Yes, I could add a try-catch block inside each action that calls the middle-tier code and set a property and the model state to invalid and redisplay the view. To be more specific with my question, I'm wondering if there is a better, more global approach to do similar functionality and not have a try-catch block in each Action method?
– LilCrabner
Jan 19 at 20:42
If you can decipher what action was called and from what controller when the exception occurs, couldn't you just redirect to that controller/action with the model with an updated model property of the exception instead of directing to the error page?
– Ryan Wilson
Jan 19 at 20:46
Add a property to your Model that holds the exception message and model bind it to your view, place at try-catch inside your Action and if an exception occurs, set the property of your model with the exception details and return the model to the View without doing a RedirectToAction
– Ryan Wilson
Jan 19 at 20:31
Add a property to your Model that holds the exception message and model bind it to your view, place at try-catch inside your Action and if an exception occurs, set the property of your model with the exception details and return the model to the View without doing a RedirectToAction
– Ryan Wilson
Jan 19 at 20:31
Yes, I could add a try-catch block inside each action that calls the middle-tier code and set a property and the model state to invalid and redisplay the view. To be more specific with my question, I'm wondering if there is a better, more global approach to do similar functionality and not have a try-catch block in each Action method?
– LilCrabner
Jan 19 at 20:42
Yes, I could add a try-catch block inside each action that calls the middle-tier code and set a property and the model state to invalid and redisplay the view. To be more specific with my question, I'm wondering if there is a better, more global approach to do similar functionality and not have a try-catch block in each Action method?
– LilCrabner
Jan 19 at 20:42
If you can decipher what action was called and from what controller when the exception occurs, couldn't you just redirect to that controller/action with the model with an updated model property of the exception instead of directing to the error page?
– Ryan Wilson
Jan 19 at 20:46
If you can decipher what action was called and from what controller when the exception occurs, couldn't you just redirect to that controller/action with the model with an updated model property of the exception instead of directing to the error page?
– Ryan Wilson
Jan 19 at 20:46
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54271101%2fhow-to-handle-an-exception-in-net-core-razor-pages-pagemodel-and-stay-on-same-v%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54271101%2fhow-to-handle-an-exception-in-net-core-razor-pages-pagemodel-and-stay-on-same-v%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Add a property to your Model that holds the exception message and model bind it to your view, place at try-catch inside your Action and if an exception occurs, set the property of your model with the exception details and return the model to the View without doing a RedirectToAction
– Ryan Wilson
Jan 19 at 20:31
Yes, I could add a try-catch block inside each action that calls the middle-tier code and set a property and the model state to invalid and redisplay the view. To be more specific with my question, I'm wondering if there is a better, more global approach to do similar functionality and not have a try-catch block in each Action method?
– LilCrabner
Jan 19 at 20:42
If you can decipher what action was called and from what controller when the exception occurs, couldn't you just redirect to that controller/action with the model with an updated model property of the exception instead of directing to the error page?
– Ryan Wilson
Jan 19 at 20:46