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

通过GET请求传递客户端本地时间至API时遇HC0013错误求助

问题描述

尝试通过GET方法将客户端当前本地时间传递至API时出现错误,必须使用客户端日期时间处理结果(不能用服务器时间),目标时间格式为"12-19-2012, 7:00:00 PM"。

UI代码

const localDateTime = new Date().toLocaleString();

await fetchDocument(`${process.env.REACT_APP_API_URL}/api/projects/${projectNumber}/${localDateTime}/${currentProjectPhase}`,
setIsBodDownloading,
instance,
history
);

API代码

[HttpGet("{projectNumber}/{localDateTime}/{projectPhase?}")]
public async Task<ActionResult> BasisOfDesign(
    [FromServices] IDbContextFactory<APIDbContext> serviceScopeFactory,
    [FromServices] ICrmProjects crmProjects,
    [FromServices] IConfiguration configuration,
    [FromServices] IEmployeeContext employeeContext,
    string projectNumber,
    string localDateTime,
    string projectPhase = null,    
    CancellationToken cancellationToken = default)
{  
    .....
    ....
 }

收到的错误信息

{"errors":[{"message":"Either the parameter query or the parameter id has to be set.","extensions":{"code":"HC0013"}}]}


错误原因与修复方案

核心问题:URL路径含未编码的特殊字符

toLocaleString()生成的时间格式包含逗号(,)和空格,这些是URL路径的保留字符,直接拼入URL会导致API路由解析失败,无法正确识别参数,从而抛出错误。

具体修复步骤

  1. 编码客户端时间参数
    在拼接URL前,用encodeURIComponent()对localDateTime编码,转义特殊字符:

    const localDateTime = new Date().toLocaleString();
    // 编码特殊字符
    const encodedDateTime = encodeURIComponent(localDateTime);
    
    await fetchDocument(`${process.env.REACT_APP_API_URL}/api/projects/${projectNumber}/${encodedDateTime}/${currentProjectPhase}`,
    setIsBodDownloading,
    instance,
    history
    );
    

    ASP.NET Core会自动解码路径中的编码参数,API端无需额外处理,localDateTime会还原为原始格式。

  2. 可选:固定时间格式(避免地域差异)
    toLocaleString()的输出会因系统/浏览器地域设置变化,若要严格保证格式为"MM-dd-yyyy, h:mm:ss tt",可以手动格式化日期:

    function formatDateTime(date) {
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const year = date.getFullYear();
        let hours = date.getHours();
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        const period = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // 把0点转为12点
        return `${month}-${day}-${year}, ${hours}:${minutes}:${seconds} ${period}`;
    }
    
    const localDateTime = formatDateTime(new Date());
    const encodedDateTime = encodeURIComponent(localDateTime);
    

内容的提问来源于stack exchange,提问作者Glory Raj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:54:42