如何在drupal中对内容进行分类和标记,出现身份验证错误?

问题描述 投票:0回答:1

我正在尝试在 Drupal 10 中向文件端点发出发布请求,获取项目的 UUID,然后向内容端点发出第二个发布请求,以将文件标记和分类为我创建的名为“Sharepoint”的内容类型资源”。我可以将第一个文件上传到文件端点,但是当我尝试将第二个文件上传到内容端点时,我收到 403 禁止错误,提示“不允许此身份验证类型”。 这是执行此操作的正确方法吗?我该如何修复此错误?我已经尝试了一切。这是我的代码:

更新代码:

@page "/upload"
@rendermode InteractiveServer
@using Microsoft.AspNetCore.Components.Forms
@using System.Net.Http
@using System.Net.Http.Headers
@using System.IO
@using Newtonsoft.Json.Linq
@using System.Text
@using System.Net

<PageTitle>Upload</PageTitle>

<h3>Upload File</h3>

<label for="fileInput">Select a file to upload:</label>
<InputFile id="fileInput" OnChange="HandleFileChange" />

<label for="tag">Choose a tag:</label>
<select @bind="tag" name="tag" id="tag">
    <option value="hr">HR</option>
    <option value="connectcare">ConnectCare</option>
</select>

<button @onclick="UploadFile">Upload File</button>

@code {
    private string uploadResult;
    private IBrowserFile selectedFile;
    private string tag;
    private List<UploadedFile> uploadedFiles = new List<UploadedFile>();

    private async Task HandleFileChange(InputFileChangeEventArgs e)
    {
        selectedFile = e.File;
    }

    private async Task<byte[]> ReadFileAsync(IBrowserFile file)
    {
        using (var memoryStream = new MemoryStream())
        {
            await file.OpenReadStream().CopyToAsync(memoryStream);
            return memoryStream.ToArray();
        }
    }

    private async Task UploadFile()
    {
        if (selectedFile == null) return;

        var handler = new HttpClientHandler()
        {
            CookieContainer = new CookieContainer(),
            UseCookies = true,
            UseDefaultCredentials = false
        };

        using (var httpClient = new HttpClient(handler))
        {
            httpClient.BaseAddress = new Uri("http://localhost/drupal10/web/");

            var authValue = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:Testingdrupal"));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authValue);

            // Prepare and send the file upload request as before
            var fileBytes = await ReadFileAsync(selectedFile);
            var fileContent = new ByteArrayContent(fileBytes);
            fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = $"\"{selectedFile.Name}\""
            };

            var fileUploadResponse = await httpClient.PostAsync("file/upload/node/article/field_file", fileContent);
            if (!fileUploadResponse.IsSuccessStatusCode)
            {
                uploadResult = "File upload failed";
                return;
            }

            var fileUploadResponseContent = await fileUploadResponse.Content.ReadAsStringAsync();
            var fileJsonResponse = JObject.Parse(fileUploadResponseContent);
            var fileId = fileJsonResponse["fid"][0]["value"].ToString();
 

            // Prepare JSON payload for creating a node
            var nodeData = new
            {
                type = new { target_id = "sharepoint_resources" },
                title = new { value = "TEST UPLOAD" },
            };


           // Assuming you have fileId and tag variables correctly set from previous operations
            var nodeContent = new StringContent(JsonConvert.SerializeObject(nodeData), Encoding.UTF8, "application/json");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var response = await httpClient.PostAsync("node?_format=json", nodeContent);

            if (response.IsSuccessStatusCode)
            {
                uploadResult = "Content posted successfully with file and tags.";
            }
            else
            {
                uploadResult = $"Failed to post content: {response.StatusCode}. Response: {await response.Content.ReadAsStringAsync()}";
            }

        }
    }
}
c# .net api drupal blazor
1个回答
0
投票

这是一个简单的修复,我只需要更改有效负载。

    // Prepare JSON payload for creating a node
    var nodeData = new
    {
        type = new { target_id = "sharepoint_resources" },
        title = new[] { new { value = "TEST UPLOAD" } },
    };
© www.soinside.com 2019 - 2024. All rights reserved.