gpt4 book ai didi

c# - asp.net core如何进行异常处理?

转载 作者:行者123 更新时间:2023-11-30 20:33:07 26 4
gpt4 key购买 nike

我必须在 asp.net core 中做异常处理我已经阅读了很多文章并且我已经在我的 startup.cs 文件中实现了它,这里是代码

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();

我有一个问题,当我的 Controller 发生异常时如何调用这段代码。

我会非常感谢你。

这是 Controller 代码-:

[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);

}

最佳答案

你不需要调用它。 UseExceptionHandler是一个使用 ExceptionHandlerMiddleware 的扩展方法。参见中间件 source code :

    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
}
}

关于c# - asp.net core如何进行异常处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40611174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com