Asp.net web api Net WebAPI返回CSS

Asp.net web api Net WebAPI返回CSS,asp.net-web-api,Asp.net Web Api,我需要编写一个Web API方法,以CSS纯文本形式返回结果,而不是默认的XML或JSON,是否需要使用特定的提供者 我尝试使用ContentResult类(),但没有成功 谢谢您应该绕过内容协商,这意味着您应该直接返回HttpResponseMessage的新实例,并自行设置内容和内容类型: return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(".hiddenVi

我需要编写一个Web API方法,以CSS纯文本形式返回结果,而不是默认的XML或JSON,是否需要使用特定的提供者

我尝试使用ContentResult类(),但没有成功


谢谢

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

return new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(".hiddenView { display: none; }", Encoding.UTF8, "text/css")
    };
用答案作为灵感。您应该能够做如下简单的事情:

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;
}

你能返回一个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;
    }

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

并且只是为了好玩,这里有一个版本也可以在self-host下工作,假设您将.css作为嵌入式文件存储在与控制器相同的文件夹中。将其存储在解决方案中的文件中非常好,因为您可以获得所有VS intellisense。我添加了一些缓存,因为这个资源可能不会有太大的变化

  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;
    }

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

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

     return Content(customCss, "text/css");
 }

只是说,我认为使用StringContent重载将内容类型指定为CSS StringContent(CSS,Encoding.UTF8,“text/CSS”)@MarkJones,这是一个很好的主意(否则它将服务器text/plain,这是可以的,但使用text/CSS更好)。我对答案进行了相应的编辑,因为WebAPI和MVC是两个完全不同的框架,看起来非常相似。不幸的是,在封面下,他们是非常不同的。这就是我编辑了几十篇文章来删除ASP.NET MVC Web API这一术语的原因之一,因为它使每个人都误以为他们是同一个框架的一部分,并且框架的组件是可互换的。