如何从WebAPI抛出异常

时间:2017-10-13 02:53:32

标签: c# exception asp.net-web-api

我有业务逻辑,它抛出异常,我需要转移到我的api控制器并显示我的webapi无法读取。我到处都有托盘。在商业逻辑中

public static Models.User Login(Models.Login model)
        {
            try
            {
                using (var db = new Data.TPX5Entities())
                {
                    var query = (from a in db.User
                                 where a.UserID == model.UserName || a.UserCode == model.UserName || a.UserName == model.UserName
                                 select new Models.User
                                 {
                                     EMail = a.EMail,
                                     IsUsed = a.IsUsed,
                                     Memo = a.Memo,
                                     MobilePhone = a.MobilePhone,
                                     Password = a.Password,
                                     Telephone = a.Telephone,
                                     UserCode = a.UserCode,
                                     UserID = a.UserID,
                                     UserName = a.UserName
                                 }).ToList();
                    if (query == null || query.Count == 0)
                    {
                        throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_UserNotFound"));
                    }
                    else if (query.Count > 1)
                    {
                        throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_UserCodeRepeat"));
                    }
                    else
                    {
                        if (query[0].Password == model.Password)
                        {
                            return query[0];
                        }
                        else
                        {
                            throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_InCorrectPassword"));
                        }
                    }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

然后web api控制器我再次使用try catch

 [HttpPost]
        public Models.User Login(Models.Login model)
        {
            Models.User mUser = null;
            try
            {
                mUser = BusinessLogic.User.Login(model);
                if (mUser == null)
                    throw new Exception("Object is null.");
            }
            catch(Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message, Encoding.UTF8), ReasonPhrase = "Login Exception" });
            }
            return mUser;
        }

然后我在我的客户端调用我使用try catch再次检查

private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty( txtUser.Text))
            {
                TPX.Core.MessageBoxHelper.ShowError(Core.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "/resource/Message/MS_FormLogin_Error_UserEmpty"));
                return;
            }
            try
            {               
                //登录系统
                string md5Password = TPX.Core.Security.MD5.GetMD5(txtPassword.Text);
                TPX.Models.Login mLogin = new TPX.Models.Login();
                mLogin.UserName = txtUser.Text.Trim();
                mLogin.Password = md5Password;
                //Retrieve User Information
                string itemJson = Newtonsoft.Json.JsonConvert.SerializeObject(mLogin);
                string userURL = GlobalParameters.Host + "api/User/Login";

                using (System.Net.WebClient webClient = new System.Net.WebClient())
                {
                    webClient.Headers["Content-Type"] = "application/json";
                    webClient.Encoding = Encoding.UTF8;
                    string sJson = webClient.UploadString(userURL, "POST", itemJson);

                    TPX.Models.User myDeserializedObj = (TPX.Models.User)Newtonsoft.Json.JsonConvert.DeserializeObject(sJson, typeof(TPX.Models.User));

                    ClientContext.Instance.UserID = myDeserializedObj.UserID;
                    ClientContext.Instance.UserCode = myDeserializedObj.UserCode;
                    ClientContext.Instance.UserName = myDeserializedObj.UserName;
                    ClientContext.Instance.Password = myDeserializedObj.Password;
                }
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (WebException ex)
            {
                TPX.Core.MessageBoxHelper.ShowException((Core.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "/resource/Message/MS_FormLogin_Ex_LoginError")),ex);
            }

        }

当我使用错误的凭据登录时需要抛出错误。现在我收到错误"远程服务器返回错误:(500)内部服务器错误',而是我想抛出我的业务逻辑抛出的确切错误。谢谢 `

2 个答案:

答案 0 :(得分:2)

不要抛出500内部服务器错误,但尝试使用特定的http代码进行通信。在您的情况下,您希望传达登录失败,请具体告诉您的客户。

使用:

 throw new HttpResponseException(HttpStatusCode.Unauthorized);

或者,这样的自定义消息:

 var msg = new  HttpResponseMessage(HttpStatusCode.Unauthorized) { 
 ReasonPhrase = "whatever you want it!" };
 hrow new HttpResponseException(msg);

答案 1 :(得分:0)

您的业务层和您的API是两回事。

除非您自己的代码发生了非常糟糕的事情,否则您不会从您的API中抛出错误。

api总是返回有意义的http代码,以及客户如何知道正在进行的操作。

示例:

[HttpPost]
    public IHttpActionResult Login(Models.Login model)
    {
        var mUser = BusinessLogic.User.Login(model);
            if (mUser == null)
                return NotFound();

        return Ok(mUser);
    }

您现在正在返回一些对客户有意义的有意义的内容,而您实际上正在帮助他们了解正在发生的事情。

有多种方法可以返回数据,这只是其中之一。

避免抛出错误,在使用的资源方面成本很高,而且越多,用户就越差。

您可以让业务层以字符串的形式返回消息,然后在API调用的结果中返回该消息,另一个响应将向您显示如何。