玩转C科技.NET

从学会做人开始认识这个世界!http://volnet.github.io

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[CodeReserve]GetAttributeFromHeader

以下代码可以从http header中获取一个attribute的值。如:

String b = GetAttributeFromHeader(ContentType, "boundary");

private static String GetAttributeFromHeader(String headerValue, String attrName) {
    if (headerValue == null)
        return null; 

    int l = headerValue.Length; 
    int k = attrName.Length; 

    // find properly separated attribute name 
    int i = 1; // start searching from 1

    while (i < l) {
        i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, attrName, i, CompareOptions.IgnoreCase); 
        if (i < 0)
            break; 
        if (i+k >= l) 
            break;
 
        char chPrev = headerValue[i-1];
        char chNext = headerValue[i+k];
        if ((chPrev == ';' || chPrev == ',' || Char.IsWhiteSpace(chPrev)) && (chNext == '=' || Char.IsWhiteSpace(chNext)))
            break; 

        i += k; 
    } 

    if (i < 0 || i >= l) 
        return null;

    // skip to '=' and the following whitespaces
    i += k; 
    while (i < l && Char.IsWhiteSpace(headerValue[i]))
        i++; 
    if (i >= l || headerValue[i] != '=') 
        return null;
    i++; 
    while (i < l && Char.IsWhiteSpace(headerValue[i]))
        i++;
    if (i >= l)
        return null; 

    // parse the value 
    String attrValue = null; 

    int j; 

    if (i < l && headerValue[i] == '"') {
        if (i == l-1)
            return null; 
        j = headerValue.IndexOf('"', i+1);
        if (j < 0 || j == i+1) 
            return null; 

        attrValue = headerValue.Substring(i+1, j-i-1).Trim(); 
    }
    else {
        for (j = i; j < l; j++) {
            if (headerValue[j] == ' ' || headerValue[j] == ',') 
                break;
        } 
 
        if (j == i)
            return null; 

        attrValue = headerValue.Substring(i, j-i).Trim();
    }
 
    return attrValue;
} 

posted on   volnet(可以叫我大V)  阅读(405)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
使用Live Messenger联系我
点击右上角即可分享
微信分享提示