添加其他链接标头

时间:2016-03-04 14:14:31

标签: nancy

这可能是一个愚蠢的问题,但如何在南希的回复中添加额外的Link标题?

我无法做到

context.Response.Headers.Add("Link", "value");

因为如果已经设置了标头,则会失败。我也不能使用扩展名

context.Response.WithHeader("Link", "value");

因为它取代了任何预先存在的标题。

那么有没有方便的方法来处理多个标题?

2 个答案:

答案 0 :(得分:2)

这是我用扩展方法做的。请注意检查链接头是否已存在

    public static Response AsCreatedResourceWithLinks(this IResponseFormatter formatter, Resource resource)
    {
        return CreateResponse(formatter, resource.Id.ToString(), resource.Links);
    }

    private static Response CreateResponse(IResponseFormatter formatter, string id, IEnumerable<ResourceLink> links = null)
    {
        string url = formatter.Context.Request.Url.ToString();
        var response = new Response { StatusCode = HttpStatusCode.Created, Headers = { { "Location", url + "/" + id } } };

        if (links != null && links.Any())
        {
            foreach (var resourceLink in links)
            {
                var link = "<" + url + "/" + resourceLink.Link + ">; anchor=\"" + url + "/" + resourceLink.Anchor + "\"; rel=\"" + resourceLink.Rel + "\"";
                if (response.Headers.ContainsKey("Link"))
                {
                    response.Headers["Link"] += "," + link;
                }
                else
                {
                    response.Headers.Add("Link", link);
                }
            }
        }

        return response;
    }

Resource & ResourceLink类看起来像这样:

public class Resource
{
    public int Id { get; set; }
    public List<ResourceLink> Links { get; set; }
}

public class ResourceLink
{
    public string Link { get; set; }
    public string Anchor { get; set; }
    public string Rel { get; set; }
}

用法如下:

Post["/"] = _ => 
{ 
  //Returns Id and Links for Location/Links headers 
  var resource = something.SaveResource(); 

  return Response.AsCreatedResourceWithLinks(resource);`
}

答案 1 :(得分:0)

根据RFC,链接标题允许以逗号(“,”)分隔的多个值。

 Link: </TheBook/chapter2>; rel="previous"; title*=UTF-8'de'letztes%20Kapitel,
       </TheBook/chapter4>; rel="next"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel

所以也许您应该手动添加多个链接,然后创建标题。

String link1 = @"</TheBook/chapter2>; rel="previous"; title*=UTF-8'de'letztes%20Kapitel";
String link2 = @"</TheBook/chapter4>; rel="next"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel";
String linkHeader = link1+","+link2;

context.Response.Headers.Add("Link", linkHeader);