2017-08-03 87 views
0

我正在製作一個Web API後端,它需要返回當前登錄用戶的名稱和角色。雖然這個作品中,問題是,我返回OK(「一些字符串」)函數返回是這樣的:WebAPI 2:如何使用IHttpActionResult返回一個原始字符串?

This XML file does not appear to have any style information associated with it. The document tree is shown below. 
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Current user: MyUser Role: MyRole</string> 

這裏是我的代碼:

[ResponseType(typeof(string))] 
    public IHttpActionResult GetCurrentUser() 
    { 
     if (User.Identity.IsAuthenticated) 
     { 
      string role = service.GetRole(User.Identity.Name); 
      if (role != null) 
      { 
       return Ok("Current user: " + User.Identity.Name + " " + "Role: " + role); 
      } 
      else 
      { 
       return Ok("Current user: " + User.Identity.Name + " " + "Role: " + "No role assigned"); 
      } 
     } 
     else 
     { 
      return BadRequest("Not authenticated"); 
     } 
    } 

我怎樣才能讓這個回報只是

當前用戶:MyUser角色:MyRole?

+0

爲什麼[ResponseType(typeof(string))]?只要回覆回覆,你是否使用郵遞員進行測試? –

+0

這是爲我的幫助頁面,所以做前端的人應該知道什麼類型的響應應該期望。它與回報實際返回無關。 – Artyomska

+0

https://stackoverflow.com/questions/37492010/asp-net-mvc-api-returning-this-xml-file-does-not-appear-to-have-any-style-infor任何幫助? –

回答

1

WebApi框架使用媒體格式化程序來序列化IHttpActionResult中的內容。您應該使用HttpResponseMessageStringContent將原始字符串發送到客戶端。

public HttpResponseMessage GetCurrentUser() 
{ 
    if (User.Identity.IsAuthenticated) 
    { 
     string role = service.GetRole(User.Identity.Name); 
     if (role != null) 
     { 
      var response = Request.CreateResponse(HttpStatusCode.OK); 
      response.Content = new StringContent("Current user: " + User.Identity.Name + " " + "Role: " + role); 
      return response; 
     } 
     else 
     { 
      var response = Request.CreateResponse(HttpStatusCode.OK); 
      response.Content = new StringContent("Current user: " + User.Identity.Name + " " + "Role: " + "No role assigned"); 
      return response; 
     } 
    } 
    else 
    { 
     //But i think better return status code here is HttpStatusCode.Unauthorized 
     var response = Request.CreateResponse(HttpStatusCode.BadRequest); 
     response.Content = new StringContent("Not authenticated"); 
     return response; 
    } 
} 
相關問題