You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用API添加Basic Auth时触发FormatException错误排查

问题原因与修正方案

你遇到的FormatException是因为Basic Auth的Authorization请求头格式不符合规范。直接传入user:pass是错误的,Basic Auth要求先将用户名:密码的字符串进行Base64编码,再加上Basic 前缀作为头的值。

修正步骤

  • 将用户名:密码拼接成字符串(比如你的"senstar:senstar")
  • 使用UTF-8编码将字符串转换为字节数组
  • 对字节数组进行Base64编码
  • 构造Authorization头的值为"Basic " + Base64编码结果

修正后的完整代码

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Text;

namespace DriverSenstarNMS
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient()) 
            {
                string url = "http://localhost/api/devices/";

                client.DefaultRequestHeaders.Clear();
                
                // 构造符合规范的Basic Auth认证头
                string credentials = "senstar:senstar";
                byte[] credentialsBytes = Encoding.UTF8.GetBytes(credentials);
                string base64Credentials = Convert.ToBase64String(credentialsBytes);
                client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Credentials}");
                
                var response = client.GetAsync(url).Result;
                var res = response.Content.ReadAsStringAsync().Result;
                dynamic r = JObject.Parse(res);

                Console.WriteLine(r);
            }
        }
    }
}

额外提示

  • 生产环境中建议用async/await异步调用HttpClient方法,避免直接用.Result导致的同步阻塞死锁问题
  • 不要硬编码用户名和密码,优先从配置文件、环境变量等安全渠道读取,提升代码安全性

内容的提问来源于stack exchange,提问作者jhon estrada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:05:19