学习009-09-03 Obtain BLOB Data from a Web API Controller Endpoint(从 Web API 控制器端点获取 BLOB 数据 )

Obtain BLOB Data from a Web API Controller Endpoint(从 Web API 控制器端点获取 BLOB 数据 )

This topic demonstrates how you can use HTTP requests to download BLOB data (file attachments) available in your data model.
本主题演示如何使用HTTP请求下载数据模型中可用的BLOB数据(文件附件)。

The application must use XPO or EF Core to enable such requests. You can access BLOB data stored in the objects that are part of your data model.
应用程序必须使用XPO或EF Core来启用此类请求。您可以访问存储在作为数据模型一部分的对象中的BLOB数据。

The endpoint can work with BLOB data stored in the following formats:
端点可以使用以以下格式存储的BLOB数据:

  • byte[]
  • System.Drawing.Image
  • IFileData
  • MediaDataObject (EF Core) / MediaDataObject (XPO)

Media File Controller Availability(媒体文件控制器可用性)

The API described in this article is available in a specially designed MVC Controller - MediaFileController. This controller is available to you regardless of how you added DevExpress Web API Service to your application. No additional option selection or customization is necessary.
本文中描述的API在专门设计的MVC控制器-MediaFileController中可用。无论您如何将DevExpress Web API Service添加到您的应用程序,您都可以使用此控制器。无需额外的选项选择或自定义。

Media File Controller API(媒体文件控制器API)

The MediaFileController class includes the following method:
MediaFileController类包括以下方法:

C# 
[HttpGet(nameof(DownloadStream))]
public IActionResult DownloadStream(
  string objectType, string objectKey, string propertyName) {
    //...
}

Corresponding Web API Endpoint:
对应的Web API端点:

/api/MediaFile/DownloadStream?objectType=...&objectKey=...&propertyName=...

Parameters allow you to identify the object type, individual object/record, and the property that contains BLOB data:
参数允许您识别对象类型、单个对象/记录以及包含BLOB数据的属性:
在这里插入图片描述

Basic Usage Example(基本用法示例)

This example demonstrates how to obtain an image from a business object.
此示例演示如何从业务对象中获取图像。

C# 
HttpClient httpClient = new HttpClient();

// Set up client Uri.
httpClient.BaseAddress = new Uri("https://localhost:5001/");

string objectTypeName = typeof(ApplicationUser).Name;
string objectKey = "C4890105-CF95-4DFA-8083-08DACE0F086B";
string propertyName = nameof(ApplicationUser.Photo);

// Send request for a photo.
string url = "/api/MediaFile/DownloadStream" + 
  $"?objectType={objectTypeName}" + 
  $"&objectKey={objectKey}" + 
  $"&propertyName={propertyName}";
var response = await httpClient.GetAsync(url);

// Parse the result from HttpResponseMessage.
var photo = await response.Content.ReadAsStringAsync();

Media File Controller Customization(媒体文件控制器自定义)

The MediaFileController class is marked with an Authorize attribute. You can only use the controller with active authorization. If you need to create an unprotected endpoint, derive your own controller from the ancestor class: MediaFilesControllerBase.
MediaFileController类被标记为Authorize属性。您只能使用具有活动授权的控制器。如果您需要创建未受保护的端点,请从祖先类:MediaFilesControllerBase派生您自己的控制器。

MediaFileController uses the following service to obtain data: IStreamService. Use this service to modify controller implementation (obtain data in a custom manner). The complete service type name is as follows:
MediaFileController使用以下服务获取数据:IStreamService。使用此服务修改控制器实现(以自定义方式获取数据)。完整的服务类型名称如下:

  • DevExpress.ExpressApp.AspNetCore.Streaming.IStreamService

Add Unit Tests for MediaFile Controller(为MediaFile控制器添加单元测试)

Follow the steps below to add unit tests to your application. This example adds tests for code that queries BLOB data (uses MediaFileController).
按照以下步骤将单元测试添加到您的应用程序。此示例为查询BLOB数据(使用MediaFileController)的代码添加测试。

1.If your solution does not include a testing project, add a new xUnit test project.
如果您的解决方案不包括测试项目,请添加一个新的xUnit测试项目。

2.Add a reference to the {SolutionName}.Blazor.Server project.
添加对{SolutionName}的引用。Blazor. Server项目。

3.Add the Microsoft.AspNetCore.Mvc.Testing package reference.
添加Microsoft. AspNetCore.Mvc. Testing包参考。

4.Add the following test to the test project.
将以下测试添加到测试项目中。

C# 
using System.Net.Http.Headers;
using System.Text;
using MySolution.Module.BusinessObjects;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;


namespace MySolution.WebAPI.Tests {
    public class MediaFileTests : IClassFixture<WebApplicationFactory<MySolution.Blazor.Server.Startup>> {
        HttpClient httpClient;
        public MediaFileTests(WebApplicationFactory<MySolution.Blazor.Server.Startup> webApplicationFactory) {
            httpClient = webApplicationFactory.CreateClient();
        }


        [Fact]
        public async System.Threading.Tasks.Task LoadApplicationUserPhotoTest() {
            string tokenString = await GetUserTokenAsync("Admin", "", "/api/Authentication/Authenticate");
            var authorizationToken = new AuthenticationHeaderValue("Bearer", tokenString);


            string userKey = //"objectKey";


            string url = $"/api/MediaFile/DownloadStream?objectType={typeof(ApplicationUser).Name}&objectKey={userKey}&propertyName={nameof(ApplicationUser.Photo)}";
            var httpRequest = new HttpRequestMessage(HttpMethod.Get, url);
            httpRequest.Headers.Authorization = authorizationToken;
            var response = await httpClient.SendAsync(httpRequest);
            var data = await response.Content.ReadAsStringAsync();
            Assert.True(data.Length > 200);
        }


        async Task<string> GetUserTokenAsync(string userName, string password, string requestPath) {
            var request = new HttpRequestMessage(HttpMethod.Post, requestPath);
            request.Content = new StringContent(
                $"{{ \"userName\": \"{userName}\", \"password\": \"{password}\" }}", Encoding.UTF8, "application/json");


            var httpResponse = await httpClient.SendAsync(request);
            if(!httpResponse.IsSuccessStatusCode) {
                throw new UnauthorizedAccessException($"Authorization request failed! Code {(int)httpResponse.StatusCode}, '{httpResponse.ReasonPhrase}'");
            }
            var tokenString = await httpResponse.Content.ReadAsStringAsync();
            return tokenString;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

汤姆•猫

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

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

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

打赏作者

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

抵扣说明:

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

余额充值