Asp.net mvc 如何强制ASP.NET Web API始终返回JSON?
默认情况下,ASP.NET Web API进行内容协商-将根据Asp.net mvc 如何强制ASP.NET Web API始终返回JSON?,asp.net-mvc,asp.net-web-api,Asp.net Mvc,Asp.net Web Api,默认情况下,ASP.NET Web API进行内容协商-将根据Accept标题返回XML或JSON或其他类型。我不需要/不想要这个,有没有一种方法(比如属性或其他东西)告诉Web API总是返回JSON?清除所有格式化程序并重新添加JSON格式化程序 GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeForm
Accept
标题返回XML或JSON或其他类型。我不需要/不想要这个,有没有一种方法(比如属性或其他东西)告诉Web API总是返回JSON?清除所有格式化程序并重新添加JSON格式化程序
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
编辑
我将它添加到Global.asax内部Application\u Start()
用JsonContentNegotiator替换IContentNegotiator:
var jsonFormatter = new JsonMediaTypeFormatter();
//optional: set serializer settings here
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
JsonContentNegotiator实现:
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(
Type type,
HttpRequestMessage request,
IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(
_jsonFormatter,
new MediaTypeHeaderValue("application/json"));
}
}
公共类JsonContentNegotiator:IContentNegotiator
{
私有只读JsonMediaTypeFormatter\u jsonFormatter;
公共JsonContentNegotiator(JsonMediaTypeFormatter格式化程序)
{
_jsonFormatter=格式化程序;
}
公共内容协商结果协商(
类型类型,
HttpRequestMessage请求,
IEnumerable格式化程序)
{
返回新的ContentNegotiationResult(
_jsonFormatter,
新的MediaTypeHeaderValue(“应用程序/json”);
}
}
如果只想对一个方法执行此操作,请将方法声明为返回HttpResponseMessage
而不是IEnumerable
,然后执行以下操作:
public HttpResponseMessage GetAllWhatever()
{
return Request.CreateResponse(HttpStatusCode.OK, new List<Whatever>(), Configuration.Formatters.JsonFormatter);
}
public HttpResponseMessage getAllWhather()
{
return Request.CreateResponse(HttpStatusCode.OK,new List(),Configuration.Formatters.JsonFormatter);
}
这段代码对于单元测试来说很痛苦,但也可能是这样的:
sut = new WhateverController() { Configuration = new HttpConfiguration() };
sut.Configuration.Formatters.Add(new Mock<JsonMediaTypeFormatter>().Object);
sut.Request = new HttpRequestMessage();
sut=newwhatevercontroller(){Configuration=newhttpconfiguration()};
添加(新的Mock().Object);
sut.Request=new-HttpRequestMessage();
受德米特里·巴甫洛夫(Dmitry Pavlov)出色答案的启发,我对其进行了轻微修改,以便可以插入任何我想要强制执行的格式化程序
德米特里的功劳
/// <summary>
/// A ContentNegotiator implementation that does not negotiate. Inspired by the film Taken.
/// </summary>
internal sealed class LiamNeesonContentNegotiator : IContentNegotiator
{
private readonly MediaTypeFormatter _formatter;
private readonly string _mimeTypeId;
public LiamNeesonContentNegotiator(MediaTypeFormatter formatter, string mimeTypeId)
{
if (formatter == null)
throw new ArgumentNullException("formatter");
if (String.IsNullOrWhiteSpace(mimeTypeId))
throw new ArgumentException("Mime type identifier string is null or whitespace.");
_formatter = formatter;
_mimeTypeId = mimeTypeId.Trim();
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(_formatter, new MediaTypeHeaderValue(_mimeTypeId));
}
}
//
///不协商的ContentCongregator实现。灵感来源于拍摄的电影。
///
内部密封类联系人协商人:IContentNegotiator
{
专用只读MediaTypeFormatter\u格式化程序;
私有只读字符串_mimeTypeId;
公共联系人协商者(MediaTypeFormatter格式化程序,字符串mimeTypeId)
{
if(格式化程序==null)
抛出新的ArgumentNullException(“格式化程序”);
if(String.IsNullOrWhiteSpace(mimeTypeId))
抛出新ArgumentException(“Mime类型标识符字符串为null或空格”);
_格式化程序=格式化程序;
_mimeTypeId=mimeTypeId.Trim();
}
public ContentNegotiationResult协商(类型类型、HttpRequestMessage请求、IEnumerable格式化程序)
{
返回新的ContentNegotiationResult(_formatter,new MediaTypeHeaderValue(_mimeTypeId));
}
}
Philip W的答案是正确的,但为了清晰和完整的工作解决方案,请编辑Global.asax.cs文件,使其如下所示:(注意,我必须将reference System.Net.Http.Formatting添加到股票生成的文件中)
这将清除XML格式化程序,从而默认为JSON格式。Yo可以在WebApiConfig.cs中使用:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
已设置正确的标题。看起来有点优雅
public JsonResult<string> TestMethod()
{
return Json("your string or object");
}
publicjsonresult TestMethod()
{
返回Json(“您的字符串或对象”);
}
适用于使用OWIN的用户
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
变成(在Startup.cs中):
public System.Web.Http.Results.JsonResult Get()
{
返回Json(新的MeineObjekt()
{
Cod=“C4666”,
付款=10.0m,
isEnough=false
});
}
您可以从GlobalConfiguration.Configuration.formatters
和哪个文件中删除除json以外的所有格式化程序。。??global.ascx..??在您的应用程序中_Start()methodFilip W刚刚得到了更好的方式:),请在这里@TienDo看到它-链接到Filip自己的博客?代码的第一部分也在哪里剪切和粘贴?我在Global.asax中没有看到“config”对象。这个变量来自哪里?这篇文章也没有解释。检查WebApiConfig.cs文件中的public static void Register(HttpConfiguration config){…}方法,该方法已由VS2012在项目创建时重新定义。这将强制JSON,因为客户端接受ing XML将获得JSON,不会得到406吗?我可以回答我自己的评论/问题:它返回XML,不管Accept
标题是什么。这打破了我虚张声势的集成,似乎与github()上的这个问题有关。我想使用这个方法,但是下面使用GlobalConfiguration…Clear()
的方法实际上是有效的。如果你想要一个方法,只需要创建一个完美的方法,那么JsonResult和Json类的完全限定名是什么?
public JsonResult<string> TestMethod()
{
return Json("your string or object");
}
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
public void Configuration(IAppBuilder app)
{
OwinConfiguration = new HttpConfiguration();
ConfigureOAuth(app);
OwinConfiguration.Formatters.Clear();
OwinConfiguration.Formatters.Add(new DynamicJsonMediaTypeFormatter());
[...]
}
public System.Web.Http.Results.JsonResult<MeineObjekt> Get()
{
return Json(new MeineObjekt()
{
Cod = "C4666",
Payment = 10.0m,
isEnough = false
});
}