簡體   English   中英

更改響應內容類型

[英]Changing Response content-type

使用 C#、.NET 核心 3.1。

我正在嘗試為特定控制器(不是項目中的所有控制器)設置響應內容類型 header 值。 目前,我有這個,但我不確定我是否做得對。 我擁有的這段代碼是否朝着正確的方向發展?

public class MyCustomFilter: ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       actionExecutedContext.Response.Headers.Add("testAddingHeader", "123456");
       //Can I do change Content-Type here too?
    }
}

在我的 controller class 中:

[MyCustomFilter()] // Do I need to use [ServiceFilter(typeof(MyActionFilterAttribute))]?
public class SampleController : Controller
{
    public IActionResult Index()
    {
        return Ok("Hello World.");
    }

更新我遵循了 Silkfire 的更好建議。

這對我有用,但我從瀏覽器得到 406。 這是否意味着內容已交付給瀏覽器但不願意呈現它,因為它不是接受的內容類型(在請求中指定)的一部分? 關鍵是響應已發送給客戶端。 謝謝!

    [Produces("application/somethingcustom")]

我通過 Fiddler 檢查了對瀏覽器的響應。 似乎原始正文內容為空 - 這是否意味着服務器正在對響應正文進行一些更改,而不僅僅是更改響應內容類型 header?

更新 2找到原因:看起來我需要編寫自己的自定義格式化程序,因為我在訪問 controller 操作時注意到了這一點:

No output formatter was found for content types to write the response.

您應該能夠使用Produces屬性在 controller 上設置全局內容類型。

[Produces("application/json")]
public class SampleController : Controller

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM