通过wcf将数据插入数据库时​​不允许使用服务方法,而插入数据服务时不允许出错

时间:2014-12-26 05:17:18

标签: wcf sql-server-2008

不允许通过wcf将数据插入数据库的服务方法,而插入数据服务时不允许出现错误 代码:Iservice

        [OperationContract]
        [WebInvoke(Method = "POST",
             UriTemplate = "/InsertEmployeeDetails",
             RequestFormat = WebMessageFormat.Json,
             ResponseFormat = WebMessageFormat.Json)]
        string InsertEmployeeDetails(EmployeeDetails empInfo);


///
code:service


        public string InsertEmployeeDetails(EmployeeDetails empInfo)
        {
            string Message;

            string connectionString = "Data Source=.; Initial Catalog=emp ;User Id=sa; Password=sql@2014";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.ConnectionString = connectionString;
                connection.Open();
                SqlCommand cmd = connection.CreateCommand();
                string sql = "insert into emp_table(name,email,phone,designation,department,fax,login_id,password) values(@name,@email,@phone,@designation,@department,@fax,@login_id,@password)";
                cmd.CommandText = sql;
                cmd.Parameters.Add(new SqlParameter("@name", empInfo.emp_name));
                cmd.Parameters.Add(new SqlParameter("@email", empInfo.emp_email));
                cmd.Parameters.Add(new SqlParameter("@phone", empInfo.emp_phone));
                cmd.Parameters.Add(new SqlParameter("@designation", empInfo.emp_designation));
                cmd.Parameters.Add(new SqlParameter("@department", empInfo.emp_department));
                cmd.Parameters.Add(new SqlParameter("@fax", empInfo.emp_fax));
                cmd.Parameters.Add(new SqlParameter("@login_id", empInfo.emp_login));
                cmd.Parameters.Add(new SqlParameter("@password", empInfo.emp_password));
                int result = cmd.ExecuteNonQuery();
                if (result == 1)
                {
                    Message = empInfo.emp_login + "Details inserted Successfully";
                }
                else
                {
                    Message = empInfo.emp_login + "Error occured, Details not inserted";
                }
                return Message;


            }
        }
////
code:web.config


<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="MetadataExchangeHttpBinding_IService1">
          <security mode="None" />
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:57137/Service1.svc/mex" binding="wsHttpBinding"
        bindingConfiguration="MetadataExchangeHttpBinding_IService1"
        contract="ServiceReference1.IService1" name="MetadataExchangeHttpBinding_IService1" />
    </client>
    <services>
      <service name="Database_WCF.Service1" behaviorConfiguration="Database_WCFService.Service1Bahaviors">
        <endpoint address="" binding="webHttpBinding" contract="Database_WCF.IService1" behaviorConfiguration="ServiceAspNetAjaxBehavior">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="Database_WCF.IService1" ></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Database_WCFService.Service1Bahaviors">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
     <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, X-Requested-With" />
          <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
        </customHeaders>
      </httpProtocol>

    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

1 个答案:

答案 0 :(得分:0)

您在客户端级别和接口级别上犯了小错误。这是正确的代码

var jsonData={ Name: name, Email: email, Phone: phone, Designation: designation, Department:    department, Fax: fax, Login_Id: loginid, Password: password };
$.ajax({
   type: "POST",
   contentType: "application/json; charset=utf-8", 
   url:"http://localhost/asd/Service1.svc/InsertEmployeeDetails",
   data: jsonData,
   dataType: "Json",            
   reloadAfterSubmit: true,
   success: function (msg) {
      jQuery("#list").jqGrid('addRowData'); 
   } 
  });
 }); 
});

接口代码

[OperationContract]
[WebInvoke(Method = "POST",UriTemplate ="/InsertEmployeeDetails?emp_name={Name}&emp_email={Email}",RequestFormat =WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
string InsertEmployeeDetails(EmployeeDetails empInfo);

有关详情,请点击此链接http://forums.asp.net/t/1702719.aspx