ASP.NET Web API가 항상 JSON을 반환하도록 강제하는 방법은 무엇입니까?
ASP.NET Web API는 기본적으로 콘텐츠 협상을 수행하며 Accept
헤더 에 따라 XML 또는 JSON 또는 기타 유형을 반환합니다 . 나는 발표 필요로하지 않습니다. Web API는 항상 JSON을 반환하도록 지시하는 방법 (속성 등)이 있습니까?
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"));
}
}
모든 포맷터를 지우고 Json 포맷터를 다시 추가하십시오.
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
편집하다
Global.asax
내부에 추가했습니다 Application_Start()
.
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());
}
}
}
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
이렇게하면 XML 포맷터가 지워 지므로 기본값은 JSON 형식입니다.
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));
}
}
한 메서드에 대해서만 수행하려면 메서드를 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();
올바른 헤더가 설정되었습니다. 좀 더 우아하게 보입니다.
public JsonResult<string> TestMethod()
{
return Json("your string or object");
}
WebApiConfig.cs에서 사용할 수 있습니다.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
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());
[...]
}
참고 URL : https://stackoverflow.com/questions/12629144/how-to-force-asp-net-web-api-to-always-return-json
'IT' 카테고리의 다른 글
SQL Server의 IsNull () 함수에 해당하는 Oracle은 무엇입니까? (0) | 2020.08.14 |
---|---|
밀리 초에서 날짜 형식 mdY H : i : su 가져 오기 오기 (0) | 2020.08.14 |
시퀀스에 둘 이상의 요소가 있습니다. (0) | 2020.08.14 |
WPF 별은 무엇을 소유하고 있는지 (Width = "100 *") (0) | 2020.08.14 |
Google 크롬에서만 "모형 양식 제어" (0) | 2020.08.14 |