根据示例调用阿里云文本内容检测时在TextScanResponse response = client.GetAcsResponse(request);这个地方报“Object reference not set to an instance of an object”
代码如下:
using System;
using Newtonsoft.Json;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Green.Model.V20180509;
using System.Collections.Generic;
namespace Admin.NET.Core
{
public class AuditServiceHelper : IAuditServiceHelper, ITransient
{
private readonly HttpClient _httpClient;
public AuditServiceHelper(IHttpClientFactory httpClient)
{
_httpClient = httpClient.CreateClient();
}
public async Task<string> GetTextAuditResult(string txt)
{
/**
* 常见获取环境变量方式:
* 获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
* 获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
var accessKeyId = App.Configuration["OSSProvider:AccessKey"];
var accessKeySecret = App.Configuration["OSSProvider:SecretKey"];
DefaultProfile profile = DefaultProfile.GetProfile(
"cn-shanghai",
accessKeyId,
accessKeySecret);
// 注意:此处实例化的client尽可能重复使用,提升检测性能。避免重复建立连接。
DefaultAcsClient client = new DefaultAcsClient(profile);
TextScanRequest request = new TextScanRequest();
request.AcceptFormat = FormatType.JSON;
request.ContentType = FormatType.JSON;
request.Method = MethodType.POST;
request.Encoding = "UTF-8";
Dictionary<string, object> task1 = new Dictionary<string, object>();
task1.Add("content", txt);
Dictionary<string, object> httpBody = new Dictionary<string, object>();
// 检测场景。文本垃圾检测请传递antispam。
httpBody.Add("scenes", new List<string> { "antispam" });
httpBody.Add("bizType", "default");
httpBody.Add("tasks", new List<Dictionary<string, object>> { task1 });
request.SetContent(System.Text.Encoding.Default.GetBytes(JsonConvert.SerializeObject(httpBody)), "utf-8", FormatType.JSON);
try
{
TextScanResponse response = client.GetAcsResponse(request);
if (response.HttpResponse.Status != 200)
{
Console.WriteLine("the request failed. status:{0}", response.HttpResponse.Status);
}
Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
return "成功";
}
}
}
这个问题通常是因为请求对象(request)或响应对象(response)的部分属性没有正确初始化导致的。请确保在调用client.GetAcsResponse(request)之前,request对象已填充了所有必需的字段,特别是文本内容。从代码看,您已经设置了一些基本参数,但请检查App.Configuration["OSSProvider:AccessKey"]和App.Configuration["OSSProvider:SecretKey"]是否正确获取了AccessKey ID和AccessKey Secret。
如果这些都设置无误,可能是其他依赖项或配置问题。确保 Newtonsoft.Json NuGet 包已安装,并检查DefaultAcsClient实例化和TextScanRequest的构造是否正常。可参考文档链接
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。