2015-12-15 5 views
2

Я хочу вставить данные в sql-сервер, вызывающий WCF в JQuery. Я не знаю, почему я получаю сообщение об ошибке, которое очень сложно проследить. Я даю код ниже. Пожалуйста, помогите.Вызов службы WCF в ошибках бросания JQuery

1) IService.cs

[ServiceContract] 
public interface IService1 
{ 

    [OperationContract] 
    [WebInvoke(Method = "POST", 
    ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] 
    string InsertUserDetails(UserDetails userInfo); 
} 

[DataContract] 
public class UserDetails 
{ 

    string empname = string.Empty; 
    string empdesignation = string.Empty; 

    [DataMember] 
    public string EmpName 
    { 
     get { return empname; } 
     set { empname = value; } 
    } 

    [DataMember] 
    public string EmpDesignation 
    { 
     get { return empdesignation; } 
     set { empdesignation = value; } 
    } 

2) Service1.svc.cs

public class Service1 : IService1 
{ 


    public string InsertUserDetails(UserDetails userInfo) 

    { 

     string Message; 


     SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=TestDB;User ID=sa;Password=abc123"); 

     con.Open(); 

     SqlCommand cmd = new SqlCommand("insert into tbl_emp(EmpName,EmpDesignation) values(@EmpName,@EmpDesignation)", con); 

     cmd.Parameters.AddWithValue("@EmpName", userInfo.EmpName); 

     cmd.Parameters.AddWithValue("@EmpDesignation", userInfo.EmpDesignation); 

     int result = cmd.ExecuteNonQuery(); 

     if (result == 1) 

     { 

      Message = userInfo.EmpName + " Details inserted successfully"; 

     } 

     else 

     { 

     Message = userInfo.EmpName + " Details not inserted successfully"; 

     } 

     con.Close(); 
     return Message; 

    } 
} 

3) Service1.svc Разметка

<%@ ServiceHost Language="C#" Debug="true" Service="MobileService.Service1" CodeBehind="Service1.svc.cs" %> 

4) 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> 

    <services> 

     <service name="MobileService.Service1" behaviorConfiguration="ServiceBehavior"> 
     <endpoint address="" binding ="webHttpBinding" contract="MobileService.IService1" behaviorConfiguration="EndPointBehavior"></endpoint> 
     <endpoint 
      address="mex" 
      binding="mexHttpBinding" 
      contract="IMetadataExchange"/> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="ServiceBehavior"> 

      <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="EndPointBehavior"> 
      <enableWebScript /> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <protocolMapping> 
     <add binding="basicHttpsBinding" scheme="https" /> 
    </protocolMapping>  
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
    <system.webServer> 
    <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"/> 

     <httpProtocol> 
     <customHeaders> 
      <add name="Access-Control-Allow-Headers" value="accept, content-type" /> 
      <add name="Access-Control-Allow-Origin" value="http://localhost" /> 
      <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" /> 
     </customHeaders> 
     </httpProtocol> 

    </system.webServer> 

</configuration> 

5) webform.aspx

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>Call WCF Service using jQuery JSON AJax Sample in Asp.net</title> 
<%--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>--%> 
    <script src="JavaScript.js"></script> 
<script type="text/javascript"> 
    try { 

     $(function() { 
      $('#tbDetails').hide(); 
      $('#btnClick').click(function() { 
       var empdata = { 
        "Empnames": "hai", 
        "empdesg": "hello" 

       }; 
       $.ajax({ 
        type: "POST", 
        contentType: "application/json; charset=utf-8", 
        url: 'http://localhost:44060/Service1.svc/InsertUserDetails', 
        //data: '{"Username": "' + $("#txtName").val() + '"}', 
        //data: '{"Empnames":'" + $("#txtName").val() + "', "empdesg":'" + $("#txtDesg").val() + "'}', 
        //data:JSON.stringify(empdata), 
        data: '{ "Empnames": "' + $("#txtName").val() + '", "empdesg": "' + $("#txtDesg").val() + '"}', 
        dataType: "json", 
        processData: false, 
        success: function (data) { 
         alert("Success") 
        }, 
        error: function (xhr, status, error) { 
         alert('Exeption:' + xhr.status + xhr.statusText); 
        } 
       }); 

      }); 
     }); 

    } 
    catch (e) { 
     alert(e); 

    } 
</script> 
<style type="text/css"> 
table,th,td 
{ 
border:1px solid black; 
border-collapse:collapse; 
} 
</style> 
</head> 
<body> 
<form id="form1" runat="server"> 
<b>Enter UserName:</b> <input type="text" id="txtName" /> 
    <b>Enter Designation:</b> <input type="text" id="txtDesg" /> 
<input type ="button" id="btnClick" value="Get Data" /> 
<table id="tbDetails" cellpadding="0" cellspacing="0"> 
<thead style="background-color:#DC5807; color:White; font-weight:bold"> 
<tr style="border:solid 1px #000000"> 
<td>UserId</td> 
<td>UserName</td> 
<td>Role</td> 
</tr> 
</thead> 
<tbody> 
</tbody> 
</table> 
</form> 
</body> 
</html> 

Я получаю ошибку, как это:

Сортировать по ключевым

ExceptionDetail

Object { Message="Object reference not set... instance of an object.", StackTrace=" at MobileService.Serv... isOperationContextSet)", Type="System.NullReferenceException", more...} 

HelpLink null

InnerException null

Сообщение Object reference not set to an instance of an object.

StackTrace

at MobileService.Service1.InsertUserDetails(UserDetails userInfo) in c:\Users\Apple\Downloads\MobileService (2)\MobileService\MobileService\Service1.svc.cs:line 42 
at SyncInvokeInsertUserDetails(Object , Object[] , Object[]) 
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) 
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) 
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)" 
+0

мы не можем видеть номера строк вашего кода в вашем представлении, пожалуйста, покажите нам, где ошибка точно выбрасывается, и вы можете получить ответ. –

ответ

0

Указывая Линия 42 Service1.svc.cs довольно сложна.

Однако, это, кажется, здесь:

if (result == 1) 
{ 
    Message = userInfo.EmpName + " Details inserted successfully"; 
} 
else 
{ 
    Message = userInfo.EmpName + " Details not inserted successfully"; 
} 

USERINFO объекта, как представляется, быть пустым. Вы можете добавить некоторый код вокруг этого, чтобы проверить значение nullability userInfo, прежде чем пытаться получить EmpName.

Поскольку код в вашем ASPX является:

data: '{ "Empnames": "' + $("#txtName").val() + '", "empdesg": "' + $("#txtDesg").val() + '"}', 

Я предполагаю, что у вас есть вопрос десериализации из Emp п AME s вместо EmpName, определенных в модели.

+0

Привет, Дидье, я поменял Empnames на EmpName и empdesg на EmpDesignation, но все же у меня такая же проблема. Я удалил, если еще часть и вернул фиктивную строку. Пожалуйста, предложите – user3589162

+0

Привет, Дидье, я продолжал пытаться поймать в публичной строке InsertUserDetails (UserDetails userInfo) и получил тело ответа как: {"d": "Ссылка объекта не установлена ​​на экземпляр объекта."} Пожалуйста, предложите следующий шаг, пожалуйста – user3589162

0

После предложения Дидье я глубоко погрузился в свою проблему и решил. Вот изменения, которые я сделал.

1) В Iservice1.CS я добавил URItemplate

[OperationContract]

[WebInvoke(Method = "POST", **UriTemplate = "InsertUserDetails"**, 

ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] 
string InsertUserDetails(UserDetails userInfo); 

2) в формате HTML на стороне клиента страница кода я модифицированного

data: '{"EmpName": "' + $("#txtName").val() + '", "EmpDesignation": "' + $("#txtDesg").val() + '"}' 

3) В web.config я изменил код добавлен <webHttp /> Вместо <enableWebScript /> потому что согласно MSDN:

< webHttp />
Этот элемент определяет настройку WebHttpBehavior на конечной точке через конфигурацию. Такое поведение при использовании в сочетании со стандартным связыванием <webHttpBinding> позволяет использовать модель веб-программирования для службы Windows Communication Foundation (WCF).

<endpointBehaviors> 
    <behavior name="EndPointBehavior"> 
     <!--<enableWebScript />--> 
     <webHttp /> 
    </behavior> 
    </endpointBehaviors> 

Спасибо за все ваши предложения.

Смежные вопросы