Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.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# 如何从WebAPI引发异常_C#_Exception_Asp.net Web Api - Fatal编程技术网

C# 如何从WebAPI引发异常

C# 如何从WebAPI引发异常,c#,exception,asp.net-web-api,C#,Exception,Asp.net Web Api,我有一个包含抛出异常的业务逻辑,我需要将其传输到我的api控制器,并在我的webapi无法读取时显示。我把托盘接住了。在业务逻辑中 public static Models.User Login(Models.Login model) { try { using (var db = new Data.TPX5Entities()) {

我有一个包含抛出异常的业务逻辑,我需要将其传输到我的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控制器重试捕获

 [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)内部服务器错误”,而我想抛出我的业务逻辑抛出的确切错误。谢谢
`

不要抛出500内部服务器错误,而是尝试使用特定的http代码进行通信。如果您希望通信登录失败,请明确告诉您的客户端

或使用:

 throw new HttpResponseException(HttpStatusCode.Unauthorized);
或者,像这样的自定义消息:

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

您的业务层和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调用的结果返回该消息,另一个响应将向您展示如何返回该消息。

实际上,我想显示我的业务逻辑异常。但我的API控制器异常不显示业务逻辑异常。在业务逻辑中,我抛出需要捕获API异常的异常然后,您需要将该异常消息发送到客户端异常。对于您的方法,这是一条用API异常编写的自定义消息。@Mdyahiya API应该捕获业务异常,然后抛出一个API异常。此API异常的消息可能是来自您的业务逻辑的消息。有意义吗?