简体   繁体   English

从Umbraco API控制器返回json作为默认值

[英]Return json as default from Umbraco API Controller

As the title says I would like to return json as default instead of XML. 如标题所示,我想将json作为默认值而不是XML返回。 In a normal Web API i can edit App_Start/WebApiConfig.cs and add the following line but I can't find where to edit the configuration in Umbraco. 在普通的Web API中,我可以编辑App_Start / WebApiConfig.cs并添加以下行,但找不到在Umbraco中编辑配置的位置。

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

I do not wan't my method to return JsonResult to achieve this. 我不需要返回JsonResult的方法来实现此目的。

I looked at a similar solution first @sebastiaan but decided to override "ApplicationStarting" instead. 我首先查看了类似的解决方案@sebastiaan,但决定改写“ ApplicationStarting”。

public class CustomApplicationEventHandler : ApplicationEventHandler
{
    protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

And the WebApiConfig class: 和WebApiConfig类:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
}

You can create a custom global.asax.cs like so: 您可以像这样创建自定义global.asax.cs:

using System;
using System.Net.Http.Headers;
using System.Web.Http;
using Umbraco.Web;

namespace MyNamespace
{
    public class CustomGlobal : UmbracoApplication
    {
        private void application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            var formatters = GlobalConfiguration.Configuration.Formatters;
            formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
    }
}

Update your global.asax as follow then, to point to your CustomGlobal class 然后如下更新您的global.asax,以指向CustomGlobal

<%@ Application Inherits="MyCustomGlobal" Language="C#" %>

This approach is bad because it returns JSON with a Content-Type of text/html . 这种方法很糟糕,因为它返回Content-Typetext/html JSON。

See the answer and comments here: https://stackoverflow.com/a/13277616/3537393 在此处查看答案和评论: https : //stackoverflow.com/a/13277616/3537393

A better solution is: https://stackoverflow.com/a/12487921/3537393 更好的解决方案是: https : //stackoverflow.com/a/12487921/3537393

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

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