2016-03-04 112 views
1

這可能是一個愚蠢的問題,但怎麼可能產生額外Link頭添加到南希的迴應?添加額外的鏈接標題

我不能這樣做,

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

因爲失敗,如果已經有一個報頭組。我也無法使用擴展名

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

因爲它會替換任何預先存在的標頭。

所以沒有一個方便的方法來處理多個頭?

回答

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);` 
} 
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); 
+0

謝謝,我知道,這不是我真正想要的;) –