学习009-06 Make HTTP Requests to the Web API from .NET Applications(从. NET应用程序向Web API发出HTTP请求)

Make HTTP Requests to the Web API from .NET Applications(从. NET应用程序向Web API发出HTTP请求)

You can send requests to a Web API service from any .NET application with the HttpClient library. Use the OData syntax to build requests.
您可以从任何Web API服务发送请求。NET应用程序与HttpClient库。使用OData语法构建请求。

Note
If you target .NET for your backend API, be sure to register your FREE copy of our Web API Service. The Solution Wizard scaffolds an OData v4 Web API Service (.NET) with integrated RBAC authorization, and CRUD operations powered by EF Core and our XPO ORM library. Among its numerous capabilities, our built-in Web API Service filters out secured server data based on permissions granted to users. Advanced/enterprise functions include audit trail, endpoints to download reports, attach files, check validation, obtain localized captions, etc. To use the free Solution Wizard (which creates the Web API Service), run the Universal Component Installer from the DevExpress Download Manager or Free 30-Day Trial pages.
如果您将. NET作为您的后端API,请务必注册我们的Web API服务的免费副本。解决方案向导搭建了一个OData v4 Web API服务(.NET),具有集成的RBAC授权,以及由EF Core和我们的XPO ORM库提供支持的CRUD操作。在其众多功能中,我们的内置Web API服务根据授予用户的权限过滤掉安全的服务器数据。高级/企业功能包括审计跟踪、下载报告的端点、附加文件、检查验证、获取本地化字幕等。要使用免费的解决方案向导(它创建Web API服务),请从DevExpress下载管理器或免费30天试用页面运行通用组件安装程序。
To manage users, roles and security permissions at runtime in WinForms, WebForms, and ASP.NET Core Blazor administrative UI/portal, use our Cross-Platform .NET App UI (XAF): Getting Started Tutorial | Demos.
要在运行时在WinForms、WebForms和ASP.NETCore Blazor管理UI/门户中管理用户、角色和安全权限,请使用我们的跨平台. NET应用程序UI(XAF):入门教程|演示。

在这里插入图片描述

See the following topics for more information on OData query options:
有关OData查询选项的更多信息,请参阅以下主题:

  • Query options overview(查询选项概述)
  • Query options usage(查询选项使用)

The examples below send requests to the Web API service available at the following address: https://localhost:44319/.
下面的示例向以下地址提供的Web API服务发送请求:https://localhost:44319/。

*Authenticate with JSON Web Tokens (JWT)(*使用JSON Web Tokens(JWT)进行身份验证)

To obtain the JWT Authentication token for further data requests, send a request to the following endpoint: api/Authentication/Authenticate. The following example uses “Sam” as a user name and an empty password:
要获取JWT身份验证令牌以进行进一步的数据请求,请向以下端点发送请求:api/Authentication/Authenticate。以下示例使用“Sam”作为用户名和空密码:

C#

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;


namespace ConsoleApp1 {
    class Program {
        static async Task Main(string[] args) {
            HttpClient httpClient = new HttpClient();


            // Obtain a JWT token.
            StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);


            // Save the token for further requests.
            var token = await response.Content.ReadAsStringAsync();


            // Set the authentication header.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        }
    }
}

Note
For more information about cookie or JWT authentication in JavaScript instead of .NET, review the JavaScript — Consume the DevExpress Backend Web API with Svelte (Part 5. Authenticate Users and Protect Data) article and the corresponding GitHub example (the src/hooks.server.js file in particular).
有关在JavaScript而不是. NET中使用cookie或JWT身份验证的更多信息,请查看JavaScript-使用带有Svelte的DevExpress后端Web API(第5部分。验证用户和保护数据)文章和相应的GitHub示例(特别是src/hooks.server.js文件)。

Authenticate with OAuth2(使用OAuth2进行身份验证)

If your Web API Service application uses OAuth2 authentication, follow the steps below to obtain an access token. The described steps assume that a user, on whose behalf you authenticate in the Web API Service, is already registered in the service’s Security System. Refer to the following topic for more information on how to configure OAuth2 on the Web API Service side: Configure the OAuth2 Azure Authentication for the Web API.
如果您的Web API服务应用程序使用OAuth2身份验证,请按照以下步骤获取访问令牌。所描述的步骤假定您代表其在Web API服务中进行身份验证的用户已在服务的安全系统中注册。有关如何在Web API服务端配置OAuth2的更多信息,请参阅以下主题:为Web API配置OAuth2 Azure身份验证。

Register the ITokenAcquisition Service(注册IToken采集服务)

Add the following lines to your client application’s startup code to register the ITokenAcquisition service:
将以下行添加到客户端应用程序的启动代码中以注册ITokenAcquiplace服务:

C#

builder.services.AddMicrosoftIdentityWebApi(Configuration, configSectionName: "Authentication:AzureAd", jwtBearerScheme: "AzureAd")
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches(); // Add this line to register the `ITokenAcquisition` service

Acquire the Access Token(获取访问令牌)

Access the ITokenAcquisition service through Dependency Injection or use the application’s ServiceProvider to resolve it:
通过依赖注入访问ITokenAcquiplace服务或使用应用程序的ServiceProvider来解决它:

C# - Dependency Injection

private readonly ITokenAcquisition _tokenAcquisition;

public YourContextConstructor(ITokenAcquisition tokenAcquisition {
    _tokenAcquisition = tokenAcquisition;
}

C# - Service Provider

_tokenAcquisition = application.ServiceProvider.GetRequiredService<ITokenAcquisition>();

After that, use the ITokenAcquisition.GetAccessTokenForUserAsync method to acquire the access token:
之后,使用ITokenAcquiption.GetAccessTokenForUserAsync方法获取访问令牌:

C#

var scopes = new[] { "scope1", "scope2" }; // Replace with the required scopes
var oAuthToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);

Create and Send a Request(创建和发送请求)

Create an HttpRequestMessage instance and assign the obtained access token to the authorization header:
创建HttpRequestMessage实例并将获得的访问令牌分配给授权头:

C#

string endPointAddress = "https://your-endpoint.com/api/endpoint";
using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, endPointAddress);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", oAuthToken);

using var responseMessage = await _httpClient.SendAsync(httpRequestMessage);

Operate with Business Objects(使用业务对象操作)

Get Business Objects(获取业务对象)

The following code retrieves the LastName and Email fields of the Employee business object where FirstName equals “Mary”:
以下代码检索FirstName等于“Mary”的员工业务对象的LastName和Email字段:

C#

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static async Task Main(string[] args) {
            HttpClient httpClient = new HttpClient();

            // Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
            StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);

            // Save the token for further requests.
            var token = await response.Content.ReadAsStringAsync();

            // Set the authentication header.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Send a request to fetch data.
            string requestAddress = "https://localhost:44319/api/odata/Employee";
            var employees = await httpClient.GetStringAsync($"{requestAddress}?$filter=FirstName eq 'Mary'&$select=LastName,Email");
            Console.WriteLine(employees);
        }
    }
}

Result

JSON {"@odata.context":"https://localhost:44319/api/odata/$metadata#Employee(LastName,Email)",
"value":[{"LastName":"Tellitson",
            "Email":"Mary_Tellitson@example.com"}]}

Create a Business Object(创建业务对象)

The code below adds a new Employee instance with the FirstName field set to “Mary” and the LastName field set to “Gordon”:
下面的代码添加了一个新的员工实例,FirstName字段设置为“Mary”,LastName字段设置为“Gordon”:

C#

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static async Task Main(string[] args) {
            HttpClient httpClient = new HttpClient();
            // Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
            StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);

            // Save the token for further requests.
            var token = await response.Content.ReadAsStringAsync();

            // Set the authentication header.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Pass data to the Web API service.
            StringContent dataHttpContent = new StringContent(@"{ ""FirstName"": ""Mary"", ""LastName"":""Gordon"" }", Encoding.UTF8, "application/json");
            var dataResponse = await httpClient.PostAsync($"{requestAddress}", dataHttpContent);
            Console.WriteLine(dataResponse.StatusCode);
        }
    }
}

Result (the dataResponse.StatusCode value): 201 Created

Get a Reference Object(获取引用对象)

You can use one of the following techniques:
您可以使用以下技术之一:

Technique 1 (Expand Query Parameter)(技巧1(展开查询参数))
The $expand OData query parameter allows you to obtain a reference business object together with the main object.
$expand OData查询参数允许您获取引用业务对象和主对象。
Technique 2 (Ref Endpoint)(技术2(参考端点))
The $ref endpoint allows you to obtain a reference business object without its main object.
$ref端点允许您在没有主对象的情况下获取引用业务对象。

Note
*If you apply the AutoExpand attribute to a referenced property, you do not need to explicitly specify the e x p a n d p a r a m e t e r i n a n O D a t a q u e r y b e c a u s e i t i s a u t o m a t i c a l l y l o a d e d a n d i t s d a t a i s i n c l u d e d i n t h e A P I r e s p o n s e . ∗ 如果将 A u t o e x p a n d 属性应用于引用的属性,则不需要在 O D a t a 查询中显式指定 expand parameter in an OData query because it is automatically loaded and its data is included in the API response.* 如果将Autoexpand属性应用于引用的属性,则不需要在OData查询中显式指定 expandparameterinanODataquerybecauseitisautomaticallyloadedanditsdataisincludedintheAPIresponse.如果将Autoexpand属性应用于引用的属性,则不需要在OData查询中显式指定expand参数,因为它是自动加载的,并且其数据包含在API响应中。

*Technique 1 (Expand Query Parameter)(*技巧1(展开查询参数))

*The example below uses e x p a n d t o g e t a n E m p l o y e e o b j e c t w i t h i t s r e l a t e d D e p a r t m e n t o b j e c t : ∗ 下面的示例使用 expand to get an Employee object with its related Department object:* 下面的示例使用 expandtogetanEmployeeobjectwithitsrelatedDepartmentobject:下面的示例使用展开来获取一个员工对象及其相关的部门对象:

C#

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static async Task Main(string[] args) {
            HttpClient httpClient = new HttpClient();

            // Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
            StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);

            // Save the token for further requests.
            var token = await response.Content.ReadAsStringAsync();

            // Set the authentication header.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Send a request to fetch data.
            string requestAddress = "https://localhost:44319/api/odata/Employee";
            var employees = await httpClient.GetStringAsync($"{requestAddress}?$filter=FirstName eq 'Mary'&$select=LastName,Email&$expand=Department");
            Console.WriteLine(employees);
        }
    }
}

Result

JSON {"@odata.context":"https://localhost:44319/api/odata/$metadata#Employee(LastName,Email,Department())",
"value":[{"LastName":"Tellitson",
           "Email":"Mary_Tellitson@example.com",
           "Department":{
                "Oid":"6eff292f-f871-4237-a22c-8a50aa747ea3",
                "Title":"Development Department",
                "Description":"The Information Technology Department manages the company's information infrastructure and online assets.",
                "Location":"Building 2",
                "Office":"205"}
        }]
}

The $expand parameter can be applied to more than one level of related business objects. The following example retrieves a data chain that consists of two related business objects:
$expand参数可以应用于多个级别的相关业务对象。以下示例检索由两个相关业务对象组成的数据链:

C#

// ...
string requestAddress = "https://localhost:44319/api/odata/Department";
var departments = await httpClient.GetStringAsync($"{requestAddress}?$select=Title&$expand=Employees($select=FirstName,LastName;$expand=Tasks($select=Subject))");
// ...

Result

JSON {"@odata.context": "https://localhost:44319/api/odata/$metadata#Department(Title,Employees(FirstName,LastName,Tasks(Subject)))",
"value": [{ "Title": "Human Resources",
             "Employees": [{ "FirstName": "Angela",
                             "LastName": "Gross",
                             "Tasks": [{ "Subject": "Create 2022 R&D Plans"},
                                       { "Subject": "Submit D&B Number to ISP for Credit Approval"},
                                       { "Subject": "Deliver R&D Plans for 2022"}]
                           },
                           { "FirstName": "Barbara",
                             "LastName": "Faircloth",
                             "Tasks": [{ "Subject": "Subject": "Deliver R&D Plans for 2022"},
                                       { "Subject": "Submit D&B Number to ISP for Credit Approval"},
                                       { "Subject": "Create 2022 R&D Plans"}]
                            }]
           },
          { "Title": "Purchasing",
            "Employees": [{ "FirstName": "Ernest",
                            "LastName": "Webb",
                            "Tasks": [{ "Subject": "Submit D&B Number to ISP for Credit Approval"},
                                       { "Subject": "Deliver R&D Plans for 2022"}]
                           },
                           ...
                         ]
          }]
}

The default max expansion depth equals two. You can change this parameter as described in the following topic: Change the Expansion Depth for Related Business Objects.
默认的最大扩展深度等于2。您可以按照以下主题中的说明更改此参数:更改相关业务对象的扩展深度。

Technique 2 (Ref Endpoint)(技术2(参考端点))

The example below gets the Employee’s Department reference object:
下面的示例获取员工部门引用对象:

C#

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static async Task Main(string[] args) {
            HttpClient httpClient = new HttpClient();

            // Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
            StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);

            // Save the token for further requests.
            var token = await response.Content.ReadAsStringAsync();

            // Set the authentication header.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Send a request to fetch data.
            string requestAddress = "https://localhost:44319/api/odata/Employee/1/Department/$ref";
            // or
            // string requestAddress = "https://localhost:44319/api/odata/Employee(1)/Department/$ref";
            var department = await httpClient.GetStringAsync(requestAddress);
            Console.WriteLine(department);
        }
    }
}

Result

JSON {"@odata.context":"https://localhost:44319/api/odata/$metadata#Department/$entity",
"ID":1,
"Title":"Development Department",
"Office":"205","Location":"Building 2",
"Description":"The Information Technology Department manages the company's information infrastructure and online assets."}

Get an Associated Collection(获取关联集合)

You can use one of the following techniques:
您可以使用以下技术之一:

Technique 1 (Expand Query Parameter)(技巧1(展开查询参数))
The $expand OData query parameter allows you to obtain objects from an associated collection together with the main object.
$expand OData查询参数允许您从关联的集合中获取对象以及主对象。
Technique 2 (Ref Endpoint)(技术2(参考端点))
The $ref endpoint allows you to obtain objects from an associated collection without its main object.
$ref端点允许您从关联的集合中获取对象,而无需其主对象。

Technique 1 (Expand Query Parameter)(技巧1(展开查询参数))

The following example gets LastName, Email, and the related Tasks collection of the Employee business object where FirstName equals “Mary”:
以下示例获取员工业务对象的LastName、电子邮件和相关任务集合,其中FirstName等于“Mary”:

C#

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static async Task Main(string[] args) {
            HttpClient httpClient = new HttpClient();

            // Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
            StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);

            // Save the token for further requests.
            var token = await response.Content.ReadAsStringAsync();

            // Set the authentication header.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Send a request to fetch data.
            string requestAddress = "https://localhost:44319/api/odata/Employee";
            var employees = await httpClient.GetStringAsync($"{requestAddress}?$filter=FirstName eq 'Mary'&$select=LastName,Email&$expand=Tasks");
            Console.WriteLine(employees);
        }
    }
}

Result

JSON {"@odata.context":"https://localhost:44319/api/odata/$metadata#Employee(LastName,Email,Tasks())",
"value":[{"LastName":"Tellitson",
           "Email":"Mary_Tellitson@example.com",
           "Tasks":[{"Oid":"b958f20a-118d-4af0-b249-94445608549d",
                     "Subject":"2022 Brochure Designs",
                     "DueDate":"2022-01-15T00:00:00+04:00",
                     "StartDate":"0001-01-01T00:00:00Z",
                     "Status":"Deferred",
                     "PercentCompleted":0,
                     "Priority":"Normal"},
                    {"Oid":"7de87fc8-4dc0-4b76-82b3-18dffdc61ba4",
                     "Subject":"Review Benefits",
                     "DueDate":"2021-10-02T00:00:00+04:00",
                     "StartDate":"2021-09-12T00:00:00+04:00",
                     "Status":"Completed",
                     "PercentCompleted":100,
                     "Priority":"Normal"},
                    {"Oid":"67d36cda-a261-489f-afa9-c8ac43e1c2ea",
                     "Subject":"Lunch Potluck",
                     "DueDate":"2021-10-03T00:00:00+04:00",
                     "StartDate":"0001-01-01T00:00:00Z",
                     "Status":"Deferred",
                     "PercentCompleted":0,
                     "Priority":"Low"}
                    ]
        }]
}
Technique 2 (Ref Endpoint)(技术2(参考端点))

The example below gets the Employee’s Tasks collection:
下面的示例获取员工的任务集合:

C#

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1 {
    class Program {
        static async Task Main(string[] args) {
            HttpClient httpClient = new HttpClient();

            // Obtain a JWT token. This example uses "Sam" as a user name and an empty password.
            StringContent httpContent = new StringContent(@"{ ""userName"": ""Sam"", ""password"": """" }", Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync("https://localhost:44319/api/Authentication/Authenticate", httpContent);

            // Save the token for further requests.
            var token = await response.Content.ReadAsStringAsync();

            // Set the authentication header.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Send a request to fetch data.
            string requestAddress = "https://localhost:44319/api/odata/Employee(1)/Tasks/$ref";
            // or
            // string requestAddress = "https://localhost:44319/api/odata/Employee/1/Tasks/$ref";
            var tasks = await httpClient.GetStringAsync(requestAddress);
            Console.WriteLine(tasks);
        }
    }  
}

Result

JSON {"@odata.context":"https://localhost:44319/api/odata/$metadata#DemoTask",
"value":[
    {
        "ID":8,
        "Subject":"Approve Overtime Pay",
        "Description":"Brett, the overtime I submitted was not paid and I'm being told it was not approved. I thought you approved this. What is the problem?\r\nBrett Wade: I did approve it. It was an error in payroll. Trying to figure it out.",
        "DueDate":"2022-04-22T00:00:00+04:00",
        "StartDate":"2022-03-28T00:00:00+04:00",
        "PercentCompleted":0,
        "Status":"Completed",
        "Priority":"Normal",
        "ActualWorkHours":15,
        "EstimatedWorkHours":19
    },
    {
        "ID":9,
        "Subject":"Move Inventory to New Warehouse",
        "Description":"Robin, you are point person to get all inventory moved to the new warehouse location. You can hire temp workers if needed.",
        "DueDate":"2022-04-24T00:00:00+04:00",
        "StartDate":null,
        "PercentCompleted":0,
        "Status":"NotStarted",
        "Priority":"Low",
        "ActualWorkHours":0,
        "EstimatedWorkHours":10
    },
    {
        "ID":10,
        "Subject":"Shipping Label Artwork",
        "Description":"Kevin wants new shipping labels and I cannot print them without the artwork from your team. Can you please hurry and send it to me.\r\nMorgan Kennedy: Send me the specs and I will work on it when I can.",
        "DueDate":"2022-04-24T00:00:00+04:00",
        "StartDate":"2022-04-19T00:00:00+04:00",
        "PercentCompleted":0,
        "Status":"InProgress",
        "Priority":"High",
        "ActualWorkHours":19,
        "EstimatedWorkHours":12
    }
]}

Assign an Object to a Reference Property(将对象分配给引用属性)

The example below sets an Employee’s Department reference property to a Department object:
下面的示例将员工的部门引用属性设置为部门对象:

Technique 1 (In Body) - XPO Only(技术1(体内)-仅限XPO)

C#

string requestAddress = "https://localhost:44318/api/odata/Employee/1";
string jsonBody = @"{ ""Department"": ""1""}";
// or
// string jsonBody = @"{ ""Department"": { ""Oid"": ""1"" }}";
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await httpClient.PatchAsync(requestAddress, content);
Console.WriteLine(response);

Result (the dataResponse.StatusCode value): 204 No Content

To clear a Reference property, send a null value. The example below assigns null to an Employee’s Department property:
要清除引用属性,请发送一个空值。下面的示例将null分配给员工部门属性:

C#

string requestAddress = "https://localhost:44318/api/odata/Employee/1";
string jsonBody = @"{ ""Department"": null }";
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await httpClient.PatchAsync(requestAddress, content);
Console.WriteLine(response);

Result (the dataResponse.StatusCode value): 204 No Content

Technique 2 (Ref Endpoint)(技术2(参考端点))

C#

string requestAddress = "https://localhost:44319/api/odata/Employee/1/Department/$ref";
string jsonBody = "{\"@odata.id\":\"https://localhost:44319/api/odata/Department/1\"}";
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await httpClient.PutAsync(requestAddress, content);
Console.WriteLine(response);

Result (the dataResponse.StatusCode value): 204 No Content

Add an Object to a Collection(将对象添加到集合)

Technique 1 (In Body) - XPO Only(技术1(体内)-仅限XPO)

The example below adds a DemoTask object to an Employee’s Tasks collection:
下面的示例将DemoTask对象添加到员工的任务集合:

C#

string requestAddress = "https://localhost:44319/api/odata/Employee/1";
string jsonBody = @"{ ""Tasks"": [ { ""Oid"": 1 } ] }";
var response = await httpClient.PatchAsync(requestAddress, content);
Console.WriteLine(response);

Result (the dataResponse.StatusCode value): 204 No Content

Technique 2 (Ref Endpoint)(技术2(参考端点))

The example below adds a DemoTask object to an Employee’s Tasks collection:
下面的示例将DemoTask对象添加到员工的任务集合:

C#

string requestAddress = "https://localhost:44319/api/odata/Employee/1/Tasks/$ref";
string jsonBody = "{\"@odata.id\":\"https://localhost:44319/api/odata/DemoTask(1)\"}";
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(requestAddress, content);
Console.WriteLine(response);

Result (the dataResponse.StatusCode value): 204 No Content

Unlink an Object from a Reference Property(取消对象与引用属性的链接)

The example below removes the Employee’s Department reference property value:
下面的示例删除了员工部门引用属性值:

C#

string requestAddress = @"https://localhost:44319/api/odata/Employee/1/Department/$ref?
                          $id=https://localhost:44319/api/odata/Department/1";
// or
// string requestAddress = @"https://localhost:44319/api/odata/Employee(1)/Department/$ref?
//                           $id=https://localhost:44319/api/odata/Department(1)";
var response = await httpClient.DeleteAsync(requestAddress);
Console.WriteLine(response)

Result (the dataResponse.StatusCode value): 204 No Content

Remove an Object from a Collection(从集合中删除对象)

The example below removes the DemoTask object from the Employee’s Tasks collection:
下面的示例从员工的任务集合中删除了DemoTask对象:

C#

string requestAddress = @"https://localhost:44319/api/odata/Employee/1/Tasks/$ref?
                          $id=https://localhost:44319/api/odata/DemoTask/1";
// or
// string requestAddress = @"https://localhost:44319/api/odata/Employee(1)/Tasks/$ref?
//                           $id=https://localhost:44319/api/odata/DemoTask(1)";
var response = await httpClient.DeleteAsync(requestAddress);
Console.WriteLine(response)

Result (the dataResponse.StatusCode value): 204 No Content

Modify an Object Assigned to a Reference Property (XPO Only)(修改分配给引用属性的对象(仅限XPO))

The example below modifies the Department object assigned to the Employee’s Department reference property:
下面的示例修改了分配给员工部门引用属性的部门对象:

C#

string requestAddress = "https://localhost:44319/api/odata/Employee/1";
string jsonBody = @"{ ""Department"": { ""Office"":""504""} }";
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await httpClient.PatchAsync(requestAddress, content);
Console.WriteLine(response);

Result (the dataResponse.StatusCode value): 204 No Content

Modify Objects Added to an Associated Collection (XPO Only)(修改添加到关联集合的对象(仅限XPO))

The example below modifies the DemoTask object with Oid=1 from the Employee’s Tasks collection. If the collection does not contain the DemoTask object with this Oid, this object will be added:
下面的示例从员工的任务集合中修改了Oid=1的DemoTask对象。如果集合不包含具有此Oid的DemoTask对象,则将添加此对象:

C#

string requestAddress = "https://localhost:44319/api/odata/Employee/1";
string jsonBody = @"{ ""Tasks"": [{ ""Oid"": ""1"", ""Subject"":""New subject""} ]}";
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await httpClient.PatchAsync(requestAddress, content);
Console.WriteLine(response);

Result (the dataResponse.StatusCode value): 204 No Content

Call an Object’s Action Method(调用对象的动作方法)

The example below demonstrates how to call an object’s method decorated with an ActionAttribute. See the Add Endpoints for Business Object Methods topic for more information on this feature and how to enable it.
下面的示例演示了如何调用用ActionAtual装饰的对象的方法。有关此功能以及如何启用它的更多信息,请参阅为业务对象方法添加端点主题。

C#

string requestAddress = "https://localhost:44319/api/odata/Task/b1fea24f-4b60-4cd9-2158-08db8797bd56/Postpone";
string jsonBody = "{\"Days\": 7}";
StringContent content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(requestAddress, content);
Console.WriteLine(response);

Result (the dataResponse.StatusCode value): 200 OK

  • 17
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汤姆•猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值