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

Microsoft Graph调用报错:Content type text/html无注册解析工厂

问题描述

我正在按照微软官方的Outlook邮件控制台应用教程操作,严格遵循步骤执行,但在发送GET请求获取收件箱邮件时,遇到如下异常:

Content type text/html does not have a factory registered to be parsed.

我尝试添加清除请求头并设置Accept为application/json的代码修复问题,但仍未解决,相关代码如下:

public static Task<MessageCollectionResponse?> GetInboxAsync(){
    // Ensure client isn't null
    _ = _userClient ??
        throw new System.NullReferenceException("Graph has not been initialized for user auth");

    return _userClient.Me
        // Only messages from Inbox folder
        .MailFolders["Inbox"]
        .Messages
        .GetAsync((config) =>
        {
            //The next two lines were added by me to try to fix the problem
            config.Headers.Clear();
            config.Headers.Add("Accept", "application/json");
            // Only request specific properties
            config.QueryParameters.Select = new[] { "from", "isRead", "receivedDateTime", "subject" };
            // Get at most 25 results
            config.QueryParameters.Top = 25;
            // Sort by received time, newest first
            config.QueryParameters.Orderby = new[] { "receivedDateTime DESC" };
        });
}
解决方案

这个错误本质是Graph API返回了HTML格式的内容(通常是错误页面),而非预期的JSON响应,核心问题不在Accept头设置,而是请求本身无效。可以按以下步骤排查修复:

  1. 删除手动操作请求头的代码
    config.Headers.Clear()会清空Graph SDK自动添加的关键请求头(比如身份验证令牌Authorization),直接导致请求无效,API返回错误页面。删掉这两行手动设置的代码,SDK会自动处理正确的请求头:

    public static Task<MessageCollectionResponse?> GetInboxAsync(){
        // Ensure client isn't null
        _ = _userClient ??
            throw new System.NullReferenceException("Graph has not been initialized for user auth");
    
        return _userClient.Me
            .MailFolders["Inbox"]
            .Messages
            .GetAsync((config) =>
            {
                config.QueryParameters.Select = new[] { "from", "isRead", "receivedDateTime", "subject" };
                config.QueryParameters.Top = 25;
                config.QueryParameters.Orderby = new[] { "receivedDateTime DESC" };
            });
    }
    
  2. 检查用户客户端初始化配置
    确认_userClient初始化时,是否正确配置了Mail.Read权限范围,且身份验证流程成功获取到了有效令牌。权限不足或认证失败时,API会返回HTML格式的错误提示。

  3. 捕获并查看实际响应内容
    添加异常捕获逻辑,直接查看API返回的HTML内容,定位具体错误原因:

    try
    {
        var response = await GetInboxAsync();
    }
    catch (ODataErrorException ex)
    {
        Console.WriteLine($"错误信息: {ex.Message}");
        Console.WriteLine($"响应内容: {ex.Response.Content}");
    }
    catch (HttpRequestException ex)
    {
        Console.WriteLine($"请求错误: {ex.Message}");
    }
    
  4. 确认应用注册权限
    登录Azure门户,检查对应应用注册是否已添加Mail.Read委托权限,且已完成管理员同意(如果是面向租户的应用)。

内容的提问来源于stack exchange,提问作者Khaled Ayman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:12:55