ASP.NET Web API 默认进行内容协商 - 将根据Accept
标头返回 XML 或 JSON 或其他类型。我不需要/想要这个,有没有办法(比如属性或其他东西)告诉 Web API 总是返回 JSON?
问问题
72664 次
10 回答
172
清除所有格式化程序并重新添加 Json 格式化程序。
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
编辑
我把它加到Global.asax
里面了Application_Start()
。
于 2012-09-27T20:13:17.173 回答
76
在 ASP.NET Web API 中仅支持 JSON –正确的方式
将 IContentNegotiator 替换为 JsonContentNegotiator:
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"));
}
}
于 2013-08-09T11:23:47.760 回答
11
Philip W 有正确的答案,但为了清晰和完整的工作解决方案,编辑您的 Global.asax.cs 文件如下所示:(注意我必须将参考 System.Net.Http.Formatting 添加到库存生成的文件中)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace BoomInteractive.TrainerCentral.Server {
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication {
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//Force JSON responses on all requests
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
}
}
}
于 2014-05-01T18:45:07.683 回答
11
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
这将清除 XML 格式化程序,因此默认为 JSON 格式。
于 2016-01-17T00:00:51.080 回答
4
受到 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));
}
}
于 2014-03-26T18:23:55.190 回答
3
这设置了正确的标题。显得优雅一些。
public JsonResult<string> TestMethod()
{
return Json("your string or object");
}
于 2017-07-24T08:40:29.747 回答
2
如果您只想对一种方法执行此操作,则将您的方法声明为返回HttpResponseMessage
而不是IEnumerable<Whatever>
执行:
public HttpResponseMessage GetAllWhatever()
{
return Request.CreateResponse(HttpStatusCode.OK, new List<Whatever>(), Configuration.Formatters.JsonFormatter);
}
这段代码对于单元测试来说很痛苦,但也可以这样:
sut = new WhateverController() { Configuration = new HttpConfiguration() };
sut.Configuration.Formatters.Add(new Mock<JsonMediaTypeFormatter>().Object);
sut.Request = new HttpRequestMessage();
于 2013-10-30T14:11:24.143 回答
1
对于那些使用 OWIN
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
变为(在 Startup.cs 中):
public void Configuration(IAppBuilder app)
{
OwinConfiguration = new HttpConfiguration();
ConfigureOAuth(app);
OwinConfiguration.Formatters.Clear();
OwinConfiguration.Formatters.Add(new DynamicJsonMediaTypeFormatter());
[...]
}
于 2018-09-26T11:10:41.187 回答
0
哟可以在 WebApiConfig.cs 中使用:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
于 2017-04-12T08:26:41.693 回答
0
public System.Web.Http.Results.JsonResult<MeineObjekt> Get()
{
return Json(new MeineObjekt()
{
Cod = "C4666",
Payment = 10.0m,
isEnough = false
});
}
于 2021-04-07T20:58:26.293 回答