You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#实现ASP.NET应用与Microsoft Dynamics Navision2016的集成交互

Hey there! Let's break down how to integrate your existing ERP with Microsoft Dynamics Navision using C#—I’ve built several integrations for NAV in similar industry contexts, so I’ll walk you through the core communication patterns and the specific operations you’re asking about.

Core Communication Approaches for Dynamics Navision with C#

NAV officially supports two primary integration methods via web services: SOAP Web Services (ideal for complex business operations, transactions, and full CRUD) and OData Web Services (great for lightweight queries and simple updates). We’ll cover both, with code examples for your use cases.

First Step: Publish NAV Web Services

Before writing C# code, you need to publish the required NAV objects as web services:

  • Open the NAV Client, search for Web Services and open the page.
  • Add entries for the objects you need:
    • For company checks: Publish the Company page (object type: Page, object ID: 2)
    • For GL account operations: Publish the G/L Account page (object type: Page, object ID: 15)
    • For payment processing: Publish a custom code unit (or use a standard one if available) that handles payment logic
  • Note the service URLs (e.g., SOAP URL for G/L Account: http://your-nav-server:7047/DynamicsNAV/WS/YourCompany/Page/G_LAccount)

SOAP is best for operations like creating ledgers, processing payments, or validating existence because it strongly types the request/response and supports complex business logic.

Setup: Add Service Reference in Visual Studio

  1. In your C# project, right-click References > Add Service Reference
  2. Paste the SOAP URL of the published NAV service, then click Go
  3. Name the reference (e.g., NavSoapService) and click OK

Example 1: Check if a Specific Company Exists

using NavSoapService;

var navClient = new Company_Service();
// Set authentication (Windows Auth is common for on-prem NAV)
navClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
navClient.Url = "http://your-nav-server:7047/DynamicsNAV/WS/System/Page/Company";

try
{
    // Query for the company by name
    var company = navClient.ReadMultiple(new Company_Filter[] { }, "", 1);
    bool companyExists = company.Any(c => c.Name.Equals("YourTargetCompany", StringComparison.OrdinalIgnoreCase));
    
    Console.WriteLine(companyExists ? "Company exists!" : "Company not found.");
}
catch (System.ServiceModel.FaultException ex)
{
    Console.WriteLine($"NAV Error: {ex.Message}");
}
finally
{
    navClient.Close();
}

Example 2: Check if a GL Account Exists

using NavSoapService;

var glClient = new G_LAccount_Service();
glClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
glClient.Url = "http://your-nav-server:7047/DynamicsNAV/WS/YourCompany/Page/G_LAccount";

try
{
    // Try to read the GL account by number
    var glAccount = glClient.Read("10000"); // Replace with your GL number
    Console.WriteLine($"GL Account {glAccount.No_} exists: {glAccount.Name}");
}
catch (System.ServiceModel.FaultException ex)
{
    // If the account doesn't exist, NAV throws a fault
    if (ex.Message.Contains("does not exist"))
    {
        Console.WriteLine("GL Account not found.");
    }
    else
    {
        Console.WriteLine($"NAV Error: {ex.Message}");
    }
}
finally
{
    glClient.Close();
}

Example 3: Create a GL Account (Ledger)

using NavSoapService;

var glClient = new G_LAccount_Service();
glClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
glClient.Url = "http://your-nav-server:7047/DynamicsNAV/WS/YourCompany/Page/G_LAccount";

try
{
    var newGlAccount = new G_LAccount();
    newGlAccount.No_ = "20000";
    newGlAccount.Name = "Construction Materials Expense";
    newGlAccount.Income_Balance = G_LAccountIncome_Balance.Balance_Account;
    newGlAccount.Account_Type = G_LAccountAccount_Type.Posting;
    
    glClient.Create(ref newGlAccount);
    Console.WriteLine($"GL Account {newGlAccount.No_} created successfully!");
}
catch (System.ServiceModel.FaultException ex)
{
    Console.WriteLine($"Failed to create GL Account: {ex.Message}");
}
finally
{
    glClient.Close();
}

Example 4: Send Payment Data to NAV

Assuming you’ve published a custom code unit (e.g., ID 50100, PaymentProcessor) that accepts payment details:

using NavSoapService;

var paymentClient = new PaymentProcessor_Service();
paymentClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
paymentClient.Url = "http://your-nav-server:7047/DynamicsNAV/WS/YourCompany/Codeunit/PaymentProcessor";

try
{
    // Call the custom method in the code unit
    bool paymentSuccess = paymentClient.ProcessPayment(
        customerNo: "CUST001",
        amount: 1500.00m,
        paymentDate: DateTime.Today,
        reference: "INV-2024-001"
    );
    
    Console.WriteLine(paymentSuccess ? "Payment processed successfully!" : "Payment failed.");
}
catch (System.ServiceModel.FaultException ex)
{
    Console.WriteLine($"Payment Error: {ex.Message}");
}
finally
{
    paymentClient.Close();
}

2. Using OData Web Services (Lightweight Queries/Updates)

OData uses RESTful endpoints and JSON/XML, making it great for simple queries or updates. You can use HttpClient in C# to interact with these endpoints.

Example: Query if a Company Exists via OData

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;

var httpClient = new HttpClient();
// Set authentication (Basic Auth example; adjust for your NAV setup)
var credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("username:password"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

var odataUrl = "http://your-nav-server:7048/DynamicsNAV/ODataV4/Company('YourCompany')/Company";
var response = await httpClient.GetAsync(odataUrl);

if (response.IsSuccessStatusCode)
{
    var jsonResponse = await response.Content.ReadAsStringAsync();
    var companies = JsonSerializer.Deserialize<JsonElement>(jsonResponse);
    bool companyExists = companies.GetProperty("value").EnumerateArray().Any(c => 
        c.GetProperty("Name").GetString().Equals("YourTargetCompany", StringComparison.OrdinalIgnoreCase)
    );
    
    Console.WriteLine(companyExists ? "Company exists!" : "Company not found.");
}
else
{
    Console.WriteLine($"OData Error: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
}

Key Tips for Reliable Integration

  • Authentication: NAV on-prem typically uses Windows Authentication (use DefaultCredentials for SOAP, or NTLM for OData) or Basic Auth (ensure it’s enabled in NAV settings).
  • Error Handling: Always wrap calls in try-catch blocks to handle NAV-specific faults (SOAP) or HTTP errors (OData). NAV returns detailed error messages that can help debug issues.
  • Version Compatibility: Double-check your NAV version’s web service URL structure (e.g., NAV 2018 uses /WS/ for SOAP, while newer versions might use /ODataV4/ for OData).
  • Testing First: Use tools like Postman to test the web service endpoints before writing C# code—this helps validate the request/response structure without code debugging.

内容的提问来源于stack exchange,提问作者Manik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:43:12