2013-07-02 59 views
2

我需要編寫一個Web API方法,將結果作爲CSS純文本返回,而不是默認的XML或JSON,是否需要使用特定提供程序?ASP.Net WebAPI返回CSS

我試過使用ContentResult類(http://msdn.microsoft.com/en-us/library/system.web.mvc.contentresult(v=vs.108).aspx),但沒有運氣。

感謝

+1

這是因爲Web API和MVC是兩個完全不同的框架,看起來非常相似。不幸的是,在封面之下他們非常不同。我之所以編輯數十篇文章來刪除術語「ASP.NET MVC Web API」的原因之一,是因爲它將每個人都認爲它們是同一框架的一部分,並且框架的組件可以互換。 –

回答

4

您應該繞過內容協商這意味着你應該直接返回的HttpResponseMessage一個新的實例,並設置內容和內容鍵入自己:

return new HttpResponseMessage(HttpStatusCode.OK) 
    { 
     Content = new StringContent(".hiddenView { display: none; }", Encoding.UTF8, "text/css") 
    }; 
+3

只是說我認爲這是值得使用重載的StringContent來指定內容類型爲CSS StringContent(css,Encoding.UTF8,「text/css」) –

+0

@MarkJones,好主意(否則它會服務器文本/平原沒問題,但如你所說,最好使用text/css)。我已經編輯了相應的答案。 –

0

使用的答案here爲靈感。你應該能夠做到這樣簡單的事情:

public HttpResponseMessage Get() 
{ 
    string css = @"h1.basic {font-size: 1.3em;padding: 5px;color: #abcdef;background: #123456;border-bottom: 3px solid #123456;margin: 0 0 4px 0;text-align: center;}"; 
    var response = new HttpResponseMessage(HttpStatusCode.OK); 
    response.Content = new StringContent(css, Encoding.UTF8, "text/css"); 
    return response; 
} 
0

你可以返回一個HttpResponseMessage,獲取文件並返回流?像這樣的東西似乎工作....

public HttpResponseMessage Get(int id) 
    { 
     var dir = HttpContext.Current.Server.MapPath("~/content/site.css"); //location of the template file 
     var stream = new FileStream(dir, FileMode.Open); 
     var response = new HttpResponseMessage 
      { 
       StatusCode = HttpStatusCode.OK, 
       Content = new StreamContent(stream) 
      }; 

     return response; 
    } 

雖然我想補充一些錯誤在那裏,如果該文件不存在等檢查....

0

而就堆在爲樂趣,假設你將.css作爲嵌入文件存儲在與控制器相同的文件夾中,這裏的版本可以在自主主機下工作。將它存儲在你的解決方案中的文件是很好的,因爲你獲得了所有VS智能感知。而且我添加了一些緩存,因爲這個資源的機會不會有太大的變化。

public HttpResponseMessage Get(int id) 
    { 

     var stream = GetType().Assembly.GetManifestResourceStream(GetType(),"site.css"); 

     var cacheControlHeader = new CacheControlHeaderValue { MaxAge= new TimeSpan(1,0,0)}; 

     var response = new HttpResponseMessage 
      { 
       StatusCode = HttpStatusCode.OK, 
       CacheControl = cacheControlHeader, 
       Content = new StreamContent(stream, Encoding.UTF8, "text/css") 
      }; 

     return response; 
    } 
相關問題