首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在asp.net内核中进行异常处理?

如何在asp.net内核中进行异常处理?
EN

Stack Overflow用户
提问于 2016-11-15 13:33:58
回答 1查看 4.5K关注 0票数 2

我必须在asp.net内核中进行异常处理--我已经阅读了很多文章,并且在我的startup.cs文件中实现了它--下面是代码

代码语言:javascript
复制
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
    {
        app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; ; // or another Status accordingly to Exception Type
                context.Response.ContentType = "application/json";

                var error = context.Features.Get<IExceptionHandlerFeature>();
                if (error != null)
                {
                    var ex = error.Error;

                    await context.Response.WriteAsync(new ErrorDto()
                    {
                        Code = 1,
                        Message = ex.Message // or your custom message
                        // other custom data
                    }.ToString(), Encoding.UTF8);
                }
            });
            app.UseMvc();

当我的控制器出现异常时,我遇到了一个如何调用此代码的问题。

我会非常感谢你的。

这是控制器代码-:

代码语言:javascript
复制
[HttpPost]
    [AllowAnonymous]
    public async Task<JsonResult> Register([FromBody] RegisterViewModel model)
    {
        int count = 1;
        int output = count / 0;
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, UserType = model.UserType };
        user.FirstName = user.UserType.Equals(Models.Entity.Constant.RECOVERY_CENTER) ? model.Name : model.FirstName;
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
            //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            user = await _userManager.FindByEmailAsync(user.Email);
            var InsertR = await RecoveryGuidance.Models.Entity.CenterGateWay.AddNewRecoveryCenter(new Models.Entity.Center { Rec_Email = user.Email, Rec_Name = user.FirstName, Rec_UserId = user.Id });
        }
        AddErrors(result);
        return Json(result);

    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-15 13:47:45

你不需要叫它。UseExceptionHandler是一种使用ExceptionHandlerMiddleware的扩展方法。参见中间件源代码

代码语言:javascript
复制
    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);// action execution occurs in try block
        }
        catch (Exception ex)
        {
           // if any middleware has an exception(includes mvc action) handle it
        }
    }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40611174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档