且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何提供的OData API创建自定义的MediaType格式

更新时间:2023-02-17 11:44:55

您可以使用 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.