Я хочу вставить данные в 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)"
мы не можем видеть номера строк вашего кода в вашем представлении, пожалуйста, покажите нам, где ошибка точно выбрасывается, и вы можете получить ответ. –