Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我想在方法中加入异常_C#_Asp.net_Entity Framework - Fatal编程技术网

C# 我想在方法中加入异常

C# 我想在方法中加入异常,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,我想在ASP.NeET实体框架中的此方法中添加异常。如何放置异常?使用try-catch捕获异常。也许,比如: [HttpPost] public IActionResult LoginPost(string Username, string Password) { User user = dbcontext.User.Where(m => m.Username == Username).FirstOrDefault(); if (user != null &&a

我想在ASP.NeET实体框架中的此方法中添加异常。如何放置异常?

使用try-catch捕获异常。也许,比如:

[HttpPost]
public IActionResult LoginPost(string Username, string Password)
{
    User user = dbcontext.User.Where(m => m.Username == Username).FirstOrDefault();

    if (user != null && user.IsPWValid(Password))
    {
        HttpContext.Session.SetString("UserId", user.Id);
        TempData["Error"] = "";
        return RedirectToAction("Index", "Products");
    }
    else
    {
        TempData["Error"] = "Try again";
        return RedirectToAction("Login", "Home");
    }
}

希望对您有所帮助。

使用哪种方法?LoginPost方法“放置异常”是什么意思?你到底想做什么?我不明白。您正在捕获异常,而不是“放置”它(无论这意味着什么)
        public IActionResult LoginPost(string Username, string Password)
        {
            User user = dbcontext.User.Where(m => m.Username == Username).FirstOrDefault();
            if (user != null && user.IsPWValid(Password))
            {
                try
                {
                    HttpContext.Session.SetString("UserId", user.Id);
                    TempData["Error"] = "";
                    return RedirectToAction("Index", "Products");
                }

                catch(Exception e)
                {
                    TempData["Error"] = "Exception occured: " + e;
                    return RedirectToAction("Login", "Home");
                }
            }

            else
            {
                TempData["Error"] = "Try again";
                return RedirectToAction("Login", "Home");
            }
        }