2016-04-15 114 views
3

在MVC 5是可能的提供狀態的說明中,e.g:如何在MVC 6中的HttpStatusCodeResult中顯示自定義消息?

return new HttpStatusCodeResult(500, "Could not connect to database");

這是使用System.Web.Mvc.HttpStatusCodeResult

在MVC 6中使用Microsoft.AspNet.Mvc.HttpStatusCodeResult唯一的參數是statusCode

Shaun Wildermuth在此post中提到了問題 - 請參閱錯誤處理。

如何在MVC 6中顯示自定義消息?

回答

1

我找到的解決方案涉及構建額外的類,但很好地處理了StatusCodeDescription的缺失。

internal class ResponseWriter : ActionResult 
    { 
     private byte[] _stringAsByteArray; 
     private int _statusCode; 
     public ResponseWriter(string stringToWrite, int statusCodeToWrite) 
     { 
      _stringAsByteArray = Encoding.ASCII.GetBytes(stringToWrite); 
      _statusCode = statusCodeToWrite; 
     } 
     public override Task ExecuteResultAsync(ActionContext context) 
     { 
      context.HttpContext.Response.StatusCode = _statusCode; 
      return context.HttpContext.Response.Body.WriteAsync(_stringAsByteArray, 0, _stringAsByteArray.Length); 
     } 

    } 

public IActionResult OKResponse() 
{ 
return new ResponseWriter("Response description!", 200); 
} 
public IActionResult BadResponse() 
{ 
return new ResponseWriter("There was an error!", 500); 
} 

幸得此博客:http://programminghave.blogspot.com/2015/04/custom-action-results-in-aspnet-5-vnext.html

我修改了StringWriterResult類的博客,包括自定義HTTP以下狀態爲INT。

請注意,您應該使用HttpStatusCode代替構造函數中的int來遵守HTTP 1.1標準。我只是用int來展示一個更簡單的例子。

希望這會有所幫助!

相關問題