This document explains how to install and use the C# SDK for the Vision AI Platform and provides code examples.
For questions about SDK integration, API usage, or the Vision AI Platform, join our support DingTalk group (ID: 23109592).
The SDK requires .NET Framework 4.5 or .NET Core 2.0 or later. If your environment does not meet these requirements, upgrade your .NET version.
Prerequisites
Before using the SDK, you need an Alibaba Cloud account and an access key. For instructions, see Create an AccessKey.
Install the SDK package for the AI category you want to use. Follow these steps:
(Recommended) Install using NuGet.
If NuGet is not installed in Visual Studio, install NuGet first.
In Visual Studio, open or create a project, and then navigate to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
Search for Facebody20191230, find AlibabaCloud.SDK.Facebody20191230 in the results, select the latest version, and click Install.
Install by using the .NET CLI. Run
dotnet add package AlibabaCloud.SDK.Facebody20191230.AI category
SDK link
GitHub link
Face and Body
Optical Character Recognition (OCR)
Product Recognition
Content Moderation
Image Recognition
Image Generation
Image Segmentation
Object Detection
Visual Search
Image Analysis and Processing
Video Generation
Video Understanding
Video Segmentation
Asynchronous Task Management
Dedicated version for server-side facial verification (20200910)
Configure environment variables
Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
An Alibaba Cloud account has full access to all API operations. We recommend that you use a RAM user for API calls or routine O&M. For more information, see Create a RAM user.
Do not save your AccessKey ID or AccessKey Secret in project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
Configure environment variables on Linux and macOS
Open a terminal in IntelliJ IDEA.
Run the following commands to configure the environment variables.
Replace
<access_key_id>with the AccessKey ID of your RAM user and<access_key_secret>with the AccessKey Secret of your RAM user. If you need to configure more permissions, see Control access permissions using a RAM policy.export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
Configure environment variables on Windows
Create a new environment variable file, add the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared. Then, restart the Windows operating system. The following example uses Windows 10.Open File Explorer, right-click This PC, and then select Properties.
In the left-side navigation pane, click Advanced system settings.
On the Advanced tab of the System Properties dialog box, click Environment Variables.
In the Environment Variables dialog box, click New.
In the New System Variable dialog box, add the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.Restart the Windows operating system for the configurations to take effect.
Code examples
The following examples use the RecognizeBankCard operation.
Image on OSS (Shanghai)
For a list of endpoints for each AI category and their available regions, see Endpoints.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
// 1. This example uses OCR. To use other features, import the package for the corresponding AI category. You can find package names in the SDK Packages table and feature names in the 'Action' parameter of the API reference. For example, to use general image segmentation (API reference: https://help.aliyun.com/document_detail/151960.html), change 'Ocr20191230' to 'Imageseg20191230' and 'RecognizeBankCard' to 'SegmentCommonImage'.
using AlibabaCloud.SDK.Ocr20191230.Models;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Initialize a client by using the AccessKey pair
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Ocr20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
{
// Initialize the configuration object AlibabaCloud.OpenApiClient.Models.Config. This object stores your AccessKey ID, AccessKey Secret, and endpoint.
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// 2. Specify the service endpoint. You must change this to the endpoint of the corresponding AI category. For a list of endpoints, see https://help.aliyun.com/document_detail/143103.html.
config.Endpoint = "ocr.cn-shanghai.aliyuncs.com";
// 3. This example uses the OCR client. For other features, use the Client class from the corresponding package.
return new AlibabaCloud.SDK.Ocr20191230.Client(config);
}
public static void Main(string[] args)
{
// 4. For instructions on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using a RAM user's access key, you must grant the RAM user the AliyunVIAPIFullAccess permission. For instructions, see https://help.aliyun.com/document_detail/145025.html.
// The AccessKey ID and AccessKey Secret are read from environment variables. You must configure the environment variables before running the example.
// This example uses the OCR client. For other features, use the Client class from the corresponding package.
AlibabaCloud.SDK.Ocr20191230.Client client = CreateClient(Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// 5. This example uses the RecognizeBankCard operation in the OCR category. To use other features, use the appropriate package and class. For parameter settings, see the API reference for the specific feature.
AlibabaCloud.SDK.Ocr20191230.Models.RecognizeBankCardRequest recognizeBankCardRequest = new AlibabaCloud.SDK.Ocr20191230.Models.RecognizeBankCardRequest();
recognizeBankCardRequest.ImageURL = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
// 6. This example calls the RecognizeBankCardWithOptions method. To call other features, you must change the method name. The method name is derived from the feature name. For example, if the feature name is SegmentCommonImage, the method name is SegmentCommonImageWithOptions.
AlibabaCloud.SDK.Ocr20191230.Models.RecognizeBankCardResponse recognizeBankCardResponse = client.RecognizeBankCardWithOptions(recognizeBankCardRequest, runtime);
// Get the complete response.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(recognizeBankCardResponse.Body));
// Get a specific field. This is just an example. The available fields depend on the feature.
Console.WriteLine(recognizeBankCardResponse.Body.Data.CardNumber);
}
catch (TeaException error)
{
// Print the error if necessary.
Console.WriteLine(error.Message);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error if necessary.
Console.WriteLine(error.Message);
}
}
}
}
The following summary outlines the parts of the code that you need to modify:
Import the correct package and classes for your AI category. You can find the package name in the SDK Packages table and the feature name in the
Actionparameter of the API reference.For example, the API reference for the general image segmentation feature shows its category is
imageseg20191230and its feature name isSegmentCommonImage. You need to changeocr20191230toimageseg20191230andRecognizeBankCardtoSegmentCommonImagein your code.Set the correct endpoint for your AI category. A mismatch between the endpoint and category returns an
InvalidAction.NotFounderror. For details, see Endpoints.Use the
Clientclass from the corresponding AI category package.Use the
RequestandResponseclasses from the corresponding AI category package.Call the client method that corresponds to your feature. Method names are generated based on feature names. For example, if the feature name is
SegmentCommonImage, the corresponding method name isSegmentCommonImageWithOptions.
Local image or public URL
The main difference from the previous example is the use of an AdvanceRequest object, such as RecognizeBankCardAdvanceRequest. The file is passed as a stream to the ImageURLObject parameter.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
// 1. This example uses OCR. To use other features, import the package for the corresponding AI category. You can find package names in the SDK Packages table and feature names in the 'Action' parameter of the API reference. For example, to use general image segmentation (API reference: https://help.aliyun.com/document_detail/151960.html), change 'Ocr20191230' to 'Imageseg20191230' and 'RecognizeBankCard' to 'SegmentCommonImage'.
using AlibabaCloud.SDK.Ocr20191230.Models;
using Tea;
using Tea.Utils;
using static System.Net.WebRequestMethods;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Initialize a client by using the AccessKey pair
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Ocr20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
{
// Initialize the configuration object AlibabaCloud.OpenApiClient.Models.Config. This object stores your AccessKey ID, AccessKey Secret, and endpoint.
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// 2. Specify the service endpoint. You must change this to the endpoint of the corresponding AI category. For a list of endpoints, see https://help.aliyun.com/document_detail/143103.html.
config.Endpoint = "ocr.cn-shanghai.aliyuncs.com";
// 3. This example uses the OCR client. For other features, use the Client class from the corresponding package.
return new AlibabaCloud.SDK.Ocr20191230.Client(config);
}
public static void Main(string[] args)
{
// 4. For instructions on how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using a RAM user's access key, you must grant the RAM user the AliyunVIAPIFullAccess permission. For instructions, see https://help.aliyun.com/document_detail/145025.html.
// The AccessKey ID and AccessKey Secret are read from environment variables. You must configure the environment variables before running the example.
// This example uses the OCR client. For other features, use the Client class from the corresponding package.
AlibabaCloud.SDK.Ocr20191230.Client client = CreateClient(Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // 5. This example uses the RecognizeBankCard operation in the OCR category. To use other features, use the appropriate package and class. For parameter settings, see the API reference for the specific feature.
AlibabaCloud.SDK.Ocr20191230.Models.RecognizeBankCardAdvanceRequest recognizeBankCardAdvanceRequest = new AlibabaCloud.SDK.Ocr20191230.Models.RecognizeBankCardAdvanceRequest();
/* Scenario 1: Use a local file
System.IO.StreamReader file = new System.IO.StreamReader(@"/path/to/your/file.jpg");
recognizeBankCardAdvanceRequest.ImageURLObject = file.BaseStream;
*/
// Scenario 2: Use any accessible URL
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
recognizeBankCardAdvanceRequest.ImageURLObject = stream;
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
// 6. This example calls the RecognizeBankCardAdvance method. To call other features, you must change the method name. The method name is derived from the feature name. For example, if the feature name is SegmentCommonImage, the method name is SegmentCommonImageAdvance.
AlibabaCloud.SDK.Ocr20191230.Models.RecognizeBankCardResponse recognizeBankCardResponse = client.RecognizeBankCardAdvance(recognizeBankCardAdvanceRequest, runtime);
// Get the complete response.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(recognizeBankCardResponse.Body));
// Get a specific field. This is just an example. The available fields depend on the feature.
Console.WriteLine(recognizeBankCardResponse.Body.Data.CardNumber);
}
catch (TeaException error)
{
// Print the error if necessary.
Console.WriteLine(error.Message);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error if necessary.
Console.WriteLine(error.Message);
}
}
}
}
The following summary outlines the parts of the code that you need to modify:
Import the correct package and classes for your AI category. You can find the package name in the SDK Packages table and the feature name in the
Actionparameter of the API reference.For example, the API reference for the general image segmentation feature shows its category is
imageseg20191230and its feature name isSegmentCommonImage. You need to changeocr20191230toimageseg20191230andRecognizeBankCardtoSegmentCommonImagein your code.Set the correct endpoint for your AI category. A mismatch between the endpoint and category returns an
InvalidAction.NotFounderror. For details, see Endpoints.Use the
Clientclass from the corresponding AI category package.Use the
RequestandResponseclasses from the corresponding AI category package.Call the client method that corresponds to your feature. Method names are generated based on feature names. For example, if the feature name is
SegmentCommonImage, the corresponding method name isSegmentCommonImageAdvance.
FAQ
How to troubleshoot API call errors?
If an API call fails, first update the SDK package to the latest version. If your project references multiple SDK packages for different categories, update all of them to the latest version to avoid potential dependency conflicts.
Latest package not in NuGet?
If you find that the latest package version displayed in the OpenAPI Portal is not available in the NuGet repository, it may be due to a synchronization delay. Please try again later or use the latest version currently available in the repository.
Technical support
If the issue persists, join the Alibaba Cloud Vision AI Platform support group on DingTalk by searching for the group ID 23109592. A technical engineer will help you resolve the issue.