如何提供的OData API创建自定义的MediaType格式 [英] How to provide custom mediatype formats for OData Api

查看:150
本文介绍了如何提供的OData API创建自定义的MediaType格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发使用ODataApiController ASP.NET应用程序。实际应用表明,用户通过查询数据,并在表中显示它的网格。我想导出到许多不同的格式,包括CSV和自定义XML格式的能力。理想情况下,我只想采取同样的OData查询网格使用,设置接受头,并取回CSV或XML。

I am developing an ASP.NET application that uses ODataApiController. The application shows users a grid by querying data and showing it in a table. I would like the ability to export to a number of different formats, including CSV and a custom XML format. Ideally, I would just take the same OData query the grid uses, set the Accepts header, and get back CSV or XML.

我创建MediaTypeFormatters做什么,我需要的,但他们只能用常规ApiController,不ODataApiController工作。看着在GitHub上code,我看到的OData有它自己的MediaTypeFormatter计划,以处理各种情况,并内置XML和JSON格式化。但我不能看到如何挂钩到这个提供自定义格式。我试图继承ODataMediaTypeFormatter,但它设置一个断点嗟。

I've created MediaTypeFormatters to do what I need, but they only work with "regular" ApiController, not ODataApiController. Looking at the code in github, I see that OData has it's own MediaTypeFormatter scheme to handle various cases, and built in XML and JSON formatters. But I can't see how to hook into this to provide custom formats. I've attempted inheriting ODataMediaTypeFormatter, but a breakpoint set on it never hits.

我在这里输出格式才真正感兴趣。如何延长Odat​​aApi输出不同的格式?

I am only really interested in output formats here. How can I extend OdataApi to output different formats?

推荐答案

您可以使用 MediaTypeFormatter 上的OData查询为好。只需添加一个新类到您的项目继承 MediaTypeFormatter 。那么这对注册添加到​​您的WebApiConfig文件:

You can use MediaTypeFormatter on OData queries as well. Just add a new class to your project that inherit MediaTypeFormatter. Then add this to your WebApiConfig file on Register:

config.Formatters.Add(new JSONPFormatter(new QueryStringMapping("$format","jsonp","application/javascript")));

如果你再与 $格式= JSONP 查询你的实体它将返回实体JSONP。你也可以用的contentType请求它应用程序/ JavaScript的获得JSONP回报。

If you then query your entity with the $format=jsonp it will return the entity as JSONP. You can also request it with the contenttype application/javascript to get a JSONP return.

下面是用于JSONP回报MediaFormatter一个完整的示例。你可以很容易改变它为你的需要:

Here is a full example for a MediaFormatter for JSONP return. You could easily change it for your need:

using MyProject.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.ServiceModel.Syndication;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using Newtonsoft.Json;


namespace SMSIdent.Modules.Formatter
{
    /// <summary>
    /// Adds a $format=jsop to all odata query
    /// </summary>
    public class JSONPFormatter : MediaTypeFormatter
    {
        private readonly string jsMIME = "application/javascript";

        public JSONPFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue(jsMIME));
        }

        public JSONPFormatter(MediaTypeMapping mediaTypeMapping) : this() 
        {

            MediaTypeMappings.Add(mediaTypeMapping);
        }

        //THis checks if you can POST or PUT to this media-formater
        public override bool CanReadType(Type type)
        {
            return false;
        }

        //this checks if you can GET this media. You can exclude or include your Resources by checking for their types
        public override bool CanWriteType(Type type)
        {
            return true;
        }

        //This actually takes the data and writes it to the response 
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
        {
            //you can cast your entity
            //MyType entity=(MyType) value;
            var callback=HttpContext.Current.Request.Params["callback"];
            return Task.Factory.StartNew(() =>
            {
                using (StreamWriter sw = new StreamWriter(writeStream))
                {
                    if (string.IsNullOrEmpty(callback))
                    {
                        callback = "values";
                    }
                    sw.Write(callback + "(" + JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.None,
                        new JsonSerializerSettings
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        }) + ")");
                }

            });
        }
    }
}

请注意:我'使用Web API 2.我并不确切地知道它是否也适用于网页API 1

Note: I'am using Web API 2. I don't know exactly if it also works in Web Api 1.

这篇关于如何提供的OData API创建自定义的MediaType格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆