简体   繁体   English

ASP.Net WebApi:以json和xml格式返回数据

[英]ASP.Net WebApi: return data in json and xml formats

My ASP.Net WebAPI needs to return data that can be consumed in XML or Json format. 我的ASP.Net WebAPI需要返回可以XML或Json格式使用的数据。 The get method returns an object that contains objects of other types and hence the Data attribute in the Response class is defined as object. get方法返回一个包含其他类型对象的对象,因此Response类中的Data属性定义为object。

Response class 回应等级

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

    public string StatusMessage { get; set; }

    public object Data { get; set; }
}

This throws an error while accepting data in XML format 接受XML格式的数据时抛出错误

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; “ ObjectContent`1”类型未能序列化内容类型“ application / xml”的响应主体; charset=utf-8'. 字符集= UTF-8' 。

However, when I change the type of Data attributed to strongly typed such as IList, it returns data in json and xml format just fine. 但是,当我更改归因于强类型(例如IList)的数据类型时,它以json和xml格式返回数据就好了。

I need the Response class to be generic so I can reuse it for multiple controllers and action. 我需要Response类是通用的,以便可以将其重用于多个控制器和操作。 How can I achieve this? 我该如何实现?

Or you can manage it by yourself. 或者,您可以自己管理它。

    [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;            
    }

You can pass format from parameters or you can read it from request headers. 您可以通过参数传递格式,也可以从请求标头中读取格式。 Also you can use StreamContent instead StringContent cause serializers like StackTrace and Newtosnoft.Json can handle it. 也可以使用StreamContent代替StringContent导致诸如StackTraceNewtosnoft之类的序列化程序.Json可以处理它。

One way to handle this is to use AddUriPathExtensionMapping in the route configuration 一种解决方法是在路由配置中使用AddUriPathExtensionMapping

In the WebApiConfig.cs 在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");

Then when you call the api you define which format the response should be in the url 然后,当您调用api时,您将定义响应的格式应该在url中

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

This was a rather circuitous approach I was taking. 这是我采用的相当circuit回的方法。 Instead of returning the response object, I am returning HttpResponse like so 而不是返回响应对象,我像这样返回HttpResponse

 return Request.CreateResponse(HttpStatusCode.OK, terms); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM