2017-08-17 102 views
1

我要開始說,請耐心等待,因爲我正在學習C#,並且我會盡我所能做到具體。向HTTPresponseMessage Web API添加換行符C#

我們在房子裏使用第三方即時通信軟件。他們增加了在Messenger中執行斜線命令以獲取特定信息的功能。他們只有開箱即用的選項是「/ weather」,爲您提供該郵遞區號的當前天氣。

我想在內部使用它來向我的用戶提供那些包含在我們的SQL Server中的信息。我的概念證明項目是使用/折扣拉動活動折扣,並且可以通過輸入/不贊成來列出該折扣中可用的項目。

我有在Visual Studio中創建的web api,並且大多數情況下它的工作正如我所願。我需要添加一些錯誤報告,但除此之外它工作得很好。我最大的問題是用戶看到的輸出。

目前我的WebAPI我歌廳這種格式回到信使:

[ 「8 - VAPE液體 - 2 $ 2.00」, 「11 - WILDBERRY INCENSE 1」,「15 - 優質雪茄折扣 - 捆紮「‘16 - 優質雪茄折扣’]

我想他們是一個換行符至少,每一個」,「理想情況下,輸出將是:

」 8 - VAPE液體 - 2 $ 2.00 「

」11 - WILDBERRY INCENSE 1「

「15 - 優質雪茄折扣 - 套餐」

「16 - 優質雪茄折扣」

這裏是我的API位指示的代碼。

public class DiscountsController : ApiController 
{ 
    private DiscountsEntities db = new DiscountsEntities(); 

    [HttpPost] 
    public HttpResponseMessage Authenticate(FormDataCollection form) 
    { 
     var message = form.Get("Message"); 

     if (message == "/discounts") 
     { 

      var ReturnedDiscounts = from d in db.Discounts 
            where d.DiscountStartDate < DateTime.Now && d.DiscountStopDate >= DateTime.Now 
            orderby d.DiscountPriority ascending 
            select string.Concat(d.DiscountPriority, " - ", d.DiscountName); 

      HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK,ReturnedDiscounts); 
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); 


      return response; 

任何幫助或援助將不勝感激。

+0

替換它? 'ReturnedDiscounts.Replace(「\」,「,」\「」+ Environment.NewLine)' - 如果這將最終呈現爲用'
'代替html。 –

+0

@AlexK。 'ReturnedDiscounts'是一個可枚舉的--WebAPI將其格式化爲逗號分隔列表。編輯:實際上它被格式化成一個JSON數組 –

+0

我試圖用變量ReturnedDiscounts替換之前,但它一直返回實際的LINQ查詢而不是結果。當它顯示查詢時沒有任何換行符時,它只在查詢中顯示/ r/n。 – BobbyDigital

回答

1

您不必在消息中返回對象。你可以只返回一個字符串....

var strResponse = string.Join("\n", ReturnedDiscounts); 

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, strResponse); 
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); 

return response; 

編輯:

如果您正在使用的WebAPI 2,你可以做到這一點,以確保它沒有報價,以及 - 這可能是更理想的

var strResponse = string.Join("\n", ReturnedDiscounts); 

return Content(strResponse); 

如果不工作,你也可以做......

return new HttpResponseMessage() 
{ 
    Content = new StringContent(strResponse, Encoding.UTF8, "text/html") 
}; 
+0

它不出現像加入 錯誤\t CS1501 \t沒有重載方法「加入」需要1個參數\t DiscountProject – BobbyDigital

+0

@BobbyDigital wrogn加入。使用'string.Join(「\ n」,ReturnedDiscounts)' – Nkosi

+0

感謝Nkosi糾正了這一點。如上所述,我最終不得不使用
。它將字符串中的實際字符放在結果中。 – BobbyDigital