Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.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# 在ASP.NET中调用WCF服务验证表单时处理异常_C#_Asp.net Mvc_Wcf_Validation_Exception Handling - Fatal编程技术网

C# 在ASP.NET中调用WCF服务验证表单时处理异常

C# 在ASP.NET中调用WCF服务验证表单时处理异常,c#,asp.net-mvc,wcf,validation,exception-handling,C#,Asp.net Mvc,Wcf,Validation,Exception Handling,当我想调用WCF服务向此添加或搜索新项目时,我无法使用句柄异常处理验证表单“该表单不能为空”。你能帮我修一下吗 WCF服务有两个功能:通过id添加新项目和搜索项目,并与数据库连接。 客户端:当我试图从WCF服务添加新项目时,我无法处理表单ASP MVC中每个字段的异常 在Services1.cs中 public class Service1 : IService1 { DBEmployees db = new DBEmployees(); public void AddEmp

当我想调用WCF服务向此添加或搜索新项目时,我无法使用句柄异常处理验证表单“该表单不能为空”。你能帮我修一下吗

WCF服务有两个功能:通过id添加新项目和搜索项目,并与数据库连接。 客户端:当我试图从WCF服务添加新项目时,我无法处理表单ASP MVC中每个字段的异常

在Services1.cs中

public class Service1 : IService1
{


    DBEmployees db = new DBEmployees();
    public void AddEmployees(tbEmployee e)
    {
        //goi tu bang
        db.tbEmployees.Add(e);


        try
        {
            db.SaveChanges();
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
        {
            Exception raise = dbEx;
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    string message = string.Format("{0}:{1}",
                        validationErrors.Entry.Entity.ToString(),
                        validationError.ErrorMessage);
                    // raise a new exception nesting  
                    // the current instance as InnerException  
                    raise = new InvalidOperationException(message, raise);
                }
            }
            throw raise;
        }


    }

    public tbEmployee SearchEmployees(string id)
    {
        foreach (var item in db.tbEmployees)
        {
            if ((item.EmployeeID.ToLower()).Contains(id.ToLower()))
            {
                return item;
            }

        }
        return null;
    }

    public List<tbEmployee> GetEmployees()
    {
        return db.tbEmployees.ToList<tbEmployee>();

    }
}
公共类服务1:IService1
{
DBEmployees db=新的DBEmployees();
公共雇员(待定)
{
//戈杜邦
db.tbEmployees.Add(e);
尝试
{
db.SaveChanges();
}
捕获(System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
异常raise=dbEx;
foreach(dbEx.EntityValidationErrors中的var validationErrors)
{
foreach(validationErrors.validationErrors中的var validationError)
{
string message=string.Format(“{0}:{1}”,
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
//引发新的异常嵌套
//将当前实例设置为InnerException
raise=新的无效操作异常(消息,raise);
}
}
抛升;
}
}
公共tbEmployee SearchEmployees(字符串id)
{
foreach(db.tbEmployees中的var项)
{
如果((item.EmployeeID.ToLower())。包含(id.ToLower())
{
退货项目;
}
}
返回null;
}
公开名单
{
返回db.tbEmployees.ToList();
}
}

如果我们想从WCF主机应用程序抛出异常,并想在客户端应用程序中捕获它, 那么我们应该使用FaultException

它主要有两种类型:1)弱型和2)储型

首先确认您的服务行为以includeExceptionDetailInFaults=“true”:

类型2)有关强类型故障异常,请参阅以下代码: WCF主机应用程序代码示例:

List<string> productsList = new List<string>(); 
try
{
    while (productsReader.Read())
    {
        string productNumber = productsReader.GetString(0);
        productsList.Add(productNumber);
    }
}catch (Exception e)
{
    throw new FaultException("Exception reading product numbers: " + e.Message, new FaultCode("Read/GetString"));
}
// Classes for passing fault information back to client applications
[DataContract]
public class DatabaseFault
{
    [DataMember]
    public string DbOperation;
    [DataMember]
    public string DbReason;
    [DataMember]
    public string DbMessage;
}
//按如下方式修改IPProductService:

[ServiceContract]
public interface IProductsService
{
    // Get the product number of every product
    [FaultContract(typeof(ConfigFault))]
    [FaultContract(typeof(DatabaseFault))]
    [OperationContract]
    List<string> ListProducts();
    …
}
try
{
    //access service code in this try block
}
catch (FaultException<DatabaseFault> df)
{
    Console.WriteLine("DatabaseFault {0}: {1}\n{2}", df.Detail.DbOperation, df.Detail.DbMessage, df.Detail.DbReason);
}
catch (FaultException e)
{
    Console.WriteLine("{0}: {1}", e.Code.Name, e.Reason);
}
[服务合同]
公共接口IPProductsService
{
//获取每个产品的产品编号
[FaultContract(类型(配置故障))]
[FaultContract(类型(数据库故障))]
[经营合同]
列出列表产品();
…
}
//修改ProductsServices类并引发错误异常,如下所示:

List<string> productsList = new List<string>(); 
try
{
    while (productsReader.Read())
    {
        string productNumber = productsReader.GetString(0);
        productsList.Add(productNumber);
    }
}catch (Exception e)
{
    DatabaseFault df = new DatabaseFault();
    df.DbOperation = "ExecuteReader";
    df.DbReason = "Exception querying the AdventureWorks database.";
    df.DbMessage = e.Message;
    throw new FaultException<DatabaseFault>(df);
}
List productsList=new List();
尝试
{
while(productsReader.Read())
{
字符串productNumber=productsReader.GetString(0);
productsList.Add(产品编号);
}
}捕获(例外e)
{
DatabaseFault df=新的DatabaseFault();
df.DbOperation=“ExecuteReader”;
df.DbReason=“查询AdventureWorks数据库时出现异常。”;
df.DbMessage=e.Message;
抛出新的FaultException(df);
}
并在WCF客户端应用程序代码中捕获异常,如下所示:

[ServiceContract]
public interface IProductsService
{
    // Get the product number of every product
    [FaultContract(typeof(ConfigFault))]
    [FaultContract(typeof(DatabaseFault))]
    [OperationContract]
    List<string> ListProducts();
    …
}
try
{
    //access service code in this try block
}
catch (FaultException<DatabaseFault> df)
{
    Console.WriteLine("DatabaseFault {0}: {1}\n{2}", df.Detail.DbOperation, df.Detail.DbMessage, df.Detail.DbReason);
}
catch (FaultException e)
{
    Console.WriteLine("{0}: {1}", e.Code.Name, e.Reason);
}
试试看
{
//访问此try块中的服务代码
}
捕获(FaultException-df)
{
WriteLine(“DatabaseFault{0}:{1}\n{2}”,df.Detail.DbOperation,df.Detail.DbMessage,df.Detail.DbReason);
}
捕获(错误异常e)
{
WriteLine(“{0}:{1}”,e.Code.Name,e.Reason);
}
有关更多详细信息,请参阅此链接:
请让我知道,这对你有用吗?

那么,你有什么问题吗?有多少人发表“我对xyz有问题”这篇文章让人惊讶不已,但从未说明实际问题。如果你的腿骨折了,你会去看医生说“我感觉不舒服”,然后让他们做多项检查来诊断病情吗?谢谢你的回答@Tim@JohnSaunders当我试图调用WCF服务添加新项目时,我无法处理异常以验证ASP.NET MVC 5中的表单“字段不能为空”。github.com/thanhhung90/EAP–您不能处理异常是什么意思?感谢您的帮助。但我只想在ASP.NET MVC web中尝试不输入任何内容时处理异常,如下图@user221252。是否要在MVC项目中验证您的模型?为此,请参考此链接:
List<string> productsList = new List<string>(); 
try
{
    while (productsReader.Read())
    {
        string productNumber = productsReader.GetString(0);
        productsList.Add(productNumber);
    }
}catch (Exception e)
{
    DatabaseFault df = new DatabaseFault();
    df.DbOperation = "ExecuteReader";
    df.DbReason = "Exception querying the AdventureWorks database.";
    df.DbMessage = e.Message;
    throw new FaultException<DatabaseFault>(df);
}
try
{
    //access service code in this try block
}
catch (FaultException<DatabaseFault> df)
{
    Console.WriteLine("DatabaseFault {0}: {1}\n{2}", df.Detail.DbOperation, df.Detail.DbMessage, df.Detail.DbReason);
}
catch (FaultException e)
{
    Console.WriteLine("{0}: {1}", e.Code.Name, e.Reason);
}