3

我需要编写一个 Web API 方法,将结果作为 CSS 纯文本返回,而不是默认的 XML 或 JSON,是否有我需要使用的特定提供程序?

我尝试使用 ContentResult 类(http://msdn.microsoft.com/en-us/library/system.web.mvc.contentresult(v=vs.108).aspx)但没有运气。

谢谢

4

5 回答 5

6

您应该绕过内容协商,这意味着您应该HttpResponseMessage直接返回一个新实例并自己设置内容和内容类型:

return new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(".hiddenView { display: none; }", Encoding.UTF8, "text/css")
    };
于 2013-07-02T09:24:32.830 回答
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;
    }

虽然如果文件不存在等我会在那里添加一些错误检查......

于 2013-07-02T09:36:12.153 回答
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;
    }
于 2013-07-02T14:10:43.023 回答
0

使用这里的答案作为灵感。你应该能够做这样简单的事情:

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;
}
于 2013-07-02T09:31:01.653 回答
0

对于使用 AspNet Core WebApi 的任何人,您都可以这样做

 [HttpGet("custom.css")]
 public IActionResult GetCustomCss()
 {
     var customCss = ".my-class { color: #fff }";

     return Content(customCss, "text/css");
 }
于 2020-12-29T01:31:16.233 回答