2017-03-17 82 views
2

我的ASP.Net WebAPI需要返回可用於XML或Json格式的數據。 get方法返回一個包含其他類型對象的對象,因此Response類中的Data屬性被定義爲對象。ASP.Net WebApi:以json和xml格式返回數據

Response類

public class Response 
{ 
    public int StatusCode { get; set; } 

    public string StatusMessage { get; set; } 

    public object Data { get; set; } 
} 

此同時接受數據以XML格式

在 'ObjectContent`1' 型未能序列化反應體內容類型「application/xml進行引發錯誤;字符集= UTF-8' 。

但是,當我更改屬於強類型的數據類型(如IList)時,它以json和xml格式返回數據就好了。

我需要Response類是通用的,所以我可以重用它用於多個控制器和操作。我怎樣才能做到這一點?

回答

0

這是我採取的一種相當迂迴的方法。而不是返回響應對象的,我回來的HttpResponse像這樣

return Request.CreateResponse(HttpStatusCode.OK, terms);
來處理這個

1

一種方法是使用AddUriPathExtensionMapping在路由配置

在WebApiConfig.cs

config.MapHttpAttributeRoutes(); 
config.Routes.MapHttpRoute(
    name: "DefaultApi", 
    routeTemplate: "api/{controller}/{format}/{id}", 
    defaults: new { format= RouteParameter.Optional, id = RouteParameter.Optional } 
); 

//Uri format config 
config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json"); 
config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml"); 

然後當你調用api時,你可以定義響應應該是哪種格式在url中

http://yourdomain.com/api/controller/xml 
http://yourdomain.com/api/controller/json 
1

或者你可以自己管理它。

[HttpGet] 
    [Auth(Roles = "User")] 
    public HttpResponseMessage Get(Guid id, [FromUri]string format = "json") 
    { 
      Guid userGuid = GetUserID(User as ClaimsPrincipal);     

      HttpStatusCode sc = HttpStatusCode.OK; 
      string sz = ""; 

      try 
      { 
       sz = SerializationHelper.Serialize(format, SomeDataRepository.GetOptions(id, userGuid)); 
      } 
      catch (Exception ex) 
      { 
       sc = HttpStatusCode.InternalServerError; 
       sz = SerializationHelper.Serialize(format, 
                new ApiErrorMessage("Error occured", 
                     ex.Message)); 
      } 

      var res = CreateResponse(sc); 
      res.Content = new StringContent(sz, Encoding.UTF8, string.Format("application/{0}", format)); 

      return res;    
    } 

您可以通過參數傳遞格式,或者您可以從請求標頭中讀取它。 您也可以使用StreamContent代替的StringContent原因串行像堆棧跟蹤Newtosnoft.Json可以處理它。