如何通过jQuery AJAX从WinForm/ASP.NET调用WCF服务?附代码示例
Hey there! Let's dig into your jQuery AJAX to ASP.NET + WCF workflow and make sure that JSON mapping works as expected. Based on what you shared, here's a structured breakdown of your code, plus key checks and implementations to get everything hooked up right:
Here's the click handler you're using to prepare the scanner settings, plus the complete AJAX logic to send the data properly:
$("#WCF").on("click", function () { var scannerSettings = { "FileType": "TEST1", "FileName": "C:\\Program Files (x86)\\something\\Sample\\ScanTest\\VCS 2008\\bin\\Debug\\image#####", "JpegQuality": "TEST2", "ScanContinue": false, "Resolution": "TEST3", "Rotation": "TEST4" // Add any other properties from your original object here }; // Full AJAX request implementation $.ajax({ url: "/Scanner/ProcessSettings", // Replace with your actual ASP.NET controller/action path type: "POST", contentType: "application/json; charset=utf-8", // Critical for proper JSON parsing data: JSON.stringify(scannerSettings), // Convert JS object to valid JSON string success: function(response) { console.log("WCF call successful:", response); // Handle success response from WCF here }, error: function(xhr, status, error) { console.error("Error calling WCF via ASP.NET:", error); } }); });
First, create a model class that mirrors your scannerSettings structure—this will enable automatic JSON binding:
public class ScannerSettings { public string FileType { get; set; } public string FileName { get; set; } public string JpegQuality { get; set; } public bool ScanContinue { get; set; } public string Resolution { get; set; } public string Rotation { get; set; } // Add matching properties for all fields in your JS object }
Next, build a controller action to accept the AJAX request, validate the data, and call your WCF service:
using System.Web.Mvc; using YourWcfServiceNamespace; // Replace with your actual WCF service namespace public class ScannerController : Controller { [HttpPost] public JsonResult ProcessSettings(ScannerSettings settings) { // Check if settings were mapped correctly if (settings == null) { return Json(new { Success = false, Message = "No settings received from client" }); } // Initialize WCF client and invoke the service method try { using (var wcfClient = new YourWcfServiceClient()) { var wcfResult = wcfClient.ProcessScannerSettings(settings); return Json(new { Success = true, Result = wcfResult }); } } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }); } } }
To ensure the ScannerSettings object maps correctly to WCF, define a Data Contract that matches the structure exactly:
using System.Runtime.Serialization; [DataContract] public class ScannerSettings { [DataMember] public string FileType { get; set; } [DataMember] public string FileName { get; set; } [DataMember] public string JpegQuality { get; set; } [DataMember] public bool ScanContinue { get; set; } [DataMember] public string Resolution { get; set; } [DataMember] public string Rotation { get; set; } // Match all properties from the JS and ASP.NET model }
Then define your WCF service contract and implementation:
[ServiceContract] public interface IScannerService { [OperationContract] string ProcessScannerSettings(ScannerSettings settings); // Adjust return type as needed } public class ScannerService : IScannerService { public string ProcessScannerSettings(ScannerSettings settings) { // Add your WCF business logic here using the mapped settings return $"Successfully processed settings for file type: {settings.FileType}"; } }
- Property Name Matching: Make sure every property name in your JS
scannerSettingsexactly matches the names in both the ASP.NET model and WCF Data Contract (case-sensitive in most setups, so keep them consistent). - AJAX Content Type: Never omit
contentType: "application/json; charset=utf-8"—this tells ASP.NET to parse the request body as JSON instead of form data. - JSON Stringification: Always use
JSON.stringify(scannerSettings)to send the data—passing the raw JS object will cause formatting issues. - WCF Configuration: Ensure your WCF service is configured to handle JSON serialization (use
webHttpBindingwithwebHttpbehavior for REST services, orbasicHttpBindingwith proper SOAP serialization). - Path Escaping: You've correctly escaped backslashes (
\\) in yourFileNameproperty—keep this, as unescaped backslashes will break the JSON structure.
内容的提问来源于stack exchange,提问作者StealthRT

