etc./StackOverFlow

Chrome을 사용하여 XML 대신 JSON을 반환하도록 ASP.NET Web API를 얻으려면 어떻게 해야 합니까?

청렴결백한 만능 재주꾼 2023. 4. 30. 00:07
반응형

질문자 :naspinski


최신 ASP.NET Web API를 사용하여 Chrome 에서 XML이 표시됩니다. 브라우저에서 볼 수 있도록 JSON 을 요청하도록 변경하려면 어떻게 해야 합니까? 나는 그것이 요청 헤더의 일부일 뿐이라고 생각합니다. 제 말이 맞습니까?



참고: 이 답변의 주석을 읽으십시오. WebAPI의 기본 오류 처리를 사용하는 경우 XSS 취약점이 발생할 수 있습니다.

MVC Web API 프로젝트의 App_Start / WebApiConfig.cs 클래스에 다음을 추가하기만 하면 됩니다.

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

그러면 대부분의 쿼리에서 JSON을 얻을 수 있지만 text/xml 을 보낼 때 XML 을 얻을 수 있습니다.

Content-Typeapplication/json 으로 필요한 경우 아래 Todd의 답변을 확인하십시오.

NameSpace System.Net.Http.Headers 사용하고 있습니다.


Felipe Leusin

WebApiConfig 에서 이 작업을 수행하면 기본적으로 JSON을 얻을 수 있지만 요청 Accept 헤더 text/xml 을 전달하면 여전히 XML을 반환할 수 있습니다.

application/xml 대한 지원이 제거됩니다.

 public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); } }

MVC 프로젝트 유형을 사용하지 않아 이 클래스가 시작되지 않은 경우 통합 방법에 대한 자세한 내용 은 이 답변을 참조하세요.


Glenn Slaven

Content-Type = application/json 도 설정되어 Firefox(JSONView 추가 기능 포함)가 응답을 JSON으로 형식화할 수 있기 때문에 훨씬 더 잘 작동합니다.

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept", "text/html", StringComparison.InvariantCultureIgnoreCase, true, "application/json"));

dmit77

나는 Felipe Leusin의 접근 방식이 가장 마음에 듭니다. 실제로 XML을 원하는 클라이언트의 콘텐츠 협상을 손상시키지 않으면서 브라우저가 JSON을 얻도록 하십시오. 나에게 유일하게 누락된 부분은 응답 헤더에 여전히 content-type: text/html이 포함되어 있다는 것입니다. 그게 왜 문제였나요? content-type을 검사하는 JSON Formatter Chrome 확장 프로그램을 사용하기 때문에 익숙한 형식을 얻지 못합니다. text/html 요청을 수락하고 application/json 응답을 반환하는 간단한 사용자 지정 포맷터로 이 문제를 해결했습니다.

 public class BrowserJsonFormatter : JsonMediaTypeFormatter { public BrowserJsonFormatter() { this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); this.SerializerSettings.Formatting = Formatting.Indented; } public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { base.SetDefaultContentHeaders(type, headers, mediaType); headers.ContentType = new MediaTypeHeaderValue("application/json"); } }

다음과 같이 등록하십시오.

 config.Formatters.Add(new BrowserJsonFormatter());

Todd Menier

MVC4 빠른 팁 #3 – ASP.Net Web API에서 XML 포맷터 제거

Global.asax 다음 줄을 추가합니다.

 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

이렇게:

 protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); BundleTable.Bundles.RegisterTemplateBundles(); GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); }

Yakir Manor

WebApiConfig.cs 에서 Register 함수 끝에 다음을 추가합니다.

 // Remove the XML formatter config.Formatters.Remove(config.Formatters.XmlFormatter);

소스 .


Michael Vashchinsky

Global.asax에서 아래 코드를 사용하고 있습니다. JSON을 가져오는 URI는 http://www.digantakumar.com/api/values?json=true

 protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json")); }

Diganta Kumar

WebAPI의 콘텐츠 협상을 살펴보십시오. 이( 1부2부 ) 놀랍도록 상세하고 철저한 블로그 게시물은 작동 방식을 설명합니다.

간단히 말해서, 당신이 옳습니다. Accept 또는 Content-Type 요청 헤더를 설정하기만 하면 됩니다. 액션이 특정 형식을 반환하도록 코딩되지 않은 경우 Accept: application/json 설정할 수 있습니다.


Aaron Daniels

질문은 Chrome 전용이므로 요청 콘텐츠 유형을 설정할 수 있는 Postman 확장 프로그램을 얻을 수 있습니다.

우편 집배원


Chris S

한 가지 빠른 옵션은 MediaTypeMapping 전문화를 사용하는 것입니다. 다음은 Application_Start 이벤트에서 QueryStringMapping을 사용하는 예입니다.

 GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("a", "b", "application/json"));

이제 URL에 쿼리 문자열 ?a=b가 포함될 때마다 Json 응답이 브라우저에 표시됩니다.


suhair

이 코드는 json을 기본값으로 만들고 XML 형식도 사용할 수 있도록 합니다. xml=true 만 추가하겠습니다.

 GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml")); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

모두 감사합니다!


jayson.centeno

브라우저를 사용하여 API를 테스트하지 마십시오.

대신 CURL 또는 Fiddler와 같은 요청을 지정할 수 있는 HTTP 클라이언트를 사용해 보십시오.

이 문제의 문제는 API가 아니라 클라이언트에 있습니다. Web API는 브라우저의 요청에 따라 올바르게 작동합니다.


dmyoko

위의 답변 대부분은 완벽합니다. XML 형식으로 형식이 지정되는 데이터를 보고 있기 때문에 XML 형식기가 적용되었음을 의미하므로 다음과 같은 HttpConfiguration 매개변수에서 XMLFormatter를 제거하면 JSON 형식을 볼 수 있습니다.

 public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Remove(config.Formatters.XmlFormatter); config.EnableSystemDiagnosticsTracing(); }

JSON이 기본 형식이기 때문에


pavan kumar

User-Agent 헤더에 "Chrome"이 포함된 경우 전역 작업 필터를 사용하여 Accept: application/xml

 internal class RemoveXmlForGoogleChromeFilter : IActionFilter { public bool AllowMultiple { get { return false; } } public async Task<HttpResponseMessage> ExecuteActionFilterAsync( HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { var userAgent = actionContext.Request.Headers.UserAgent.ToString(); if (userAgent.Contains("Chrome")) { var acceptHeaders = actionContext.Request.Headers.Accept; var header = acceptHeaders.SingleOrDefault( x => x.MediaType.Contains("application/xml")); acceptHeaders.Remove(header); } return await continuation(); } }

작동하는 것 같습니다.


Roger Lipscombe

올바른 형식을 반환하는 것은 미디어 유형 포맷터에 의해 수행됩니다. WebApiConfig 클래스에서 이 작업을 수행할 수 있습니다.

 public static class WebApiConfig { public static void Register(HttpConfiguration config) { ... // Configure Web API to return JSON config.Formatters.JsonFormatter .SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html")); ... } }

자세한 내용은 다음을 확인하세요.

작업이 XML을 반환하고(기본값) JSON을 반환하는 특정 메서드만 필요한 경우 ActionFilterAttribute 를 사용하여 해당 특정 작업에 적용할 수 있습니다.

필터 속성:

 public class JsonOutputAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { ObjectContent content = actionExecutedContext.Response.Content as ObjectContent; var value = content.Value; Type targetType = actionExecutedContext.Response.Content.GetType().GetGenericArguments()[0]; var httpResponseMsg = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, RequestMessage = actionExecutedContext.Request, Content = new ObjectContent(targetType, value, new JsonMediaTypeFormatter(), (string)null) }; actionExecutedContext.Response = httpResponseMsg; base.OnActionExecuted(actionExecutedContext); } }

행동에 적용하기:

 [JsonOutput] public IEnumerable<Person> GetPersons() { return _repository.AllPersons(); // the returned output will be in JSON }

당신이 단어를 생략 할 수 있음을 참고 Attribute 조치 장식을 그냥 사용 [JsonOutput] 대신 [JsonOutputAttribute] .


Stacked

Chrome 앱 "고급 REST 클라이언트"가 REST 서비스와 함께 작동하는 데 탁월하다는 것을 알았습니다. Content-Type을 무엇보다도 application/json 설정할 수 있습니다. 고급 REST 클라이언트


Mike Rowley

최신 버전의 ASP.net WebApi 2에 따라,

WebApiConfig.cs 아래에서 작동합니다.

 config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); config.Formatters.Add(GlobalConfiguration.Configuration.Formatters.JsonFormatter);

A.T.

        config.Formatters.Remove(config.Formatters.XmlFormatter);

Gaurav Dubey

답변에 이 모든 복잡성이 있는 이유가 명확하지 않습니다. 물론 QueryString, 헤더 및 옵션을 사용하여 이를 수행할 수 있는 방법이 많이 있습니다. 하지만 가장 좋은 방법은 간단합니다. 일반 URL(예: http://yourstartup.com/api/cars )을 요청하고 그 대가로 JSON을 받습니다. 적절한 응답 헤더가 있는 JSON을 얻습니다.

 Content-Type: application/json

이 동일한 질문에 대한 답변을 찾는 중에 이 스레드를 찾았고 이 허용된 답변이 정확히 작동하지 않기 때문에 계속 진행해야 했습니다. 나는 내가 생각하기에 너무 단순해서 최고의 답이 아니라고 생각하는 답을 찾았습니다.

기본 WebAPI 포맷터 설정

여기에도 제 팁을 추가하겠습니다.

 WebApiConfig.cs namespace com.yourstartup { using ...; using System.Net.Http.Formatting; ... config.Formatters.Clear(); //because there are defaults of XML.. config.Formatters.Add(new JsonMediaTypeFormatter()); }

기본값(적어도 내가 보고 있는 것)이 어디에서 왔는지에 대한 질문이 있습니다. .NET 기본값입니까, 아니면 다른 곳에서 만들었는지(내 프로젝트의 다른 사람이). 어쨌든 이것이 도움이되기를 바랍니다.


Nick

아래와 같이 사용할 수 있습니다.

 GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

Akshay Kapoor

다음은 jayson.centeno System.Net.Http.Formatting 의 기본 제공 확장을 사용합니다.

 public static void Register(HttpConfiguration config) { // add support for the 'format' query param // cref: http://blogs.msdn.com/b/hongyes/archive/2012/09/02/support-format-in-asp-net-web-api.aspx config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json"); config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); // ... additional configuration }

이 솔루션은 주로 WebApi의 초기 릴리스에서 OData에 대해 $format을 지원하는 데 중점을 두었지만 OData가 아닌 구현에도 적용되며 Content-Type: application/json; charset=utf-8 응답의 Content-Type: application/json; charset=utf-8

브라우저로 테스트할 때 URI 끝에 &$format=json 또는 &$format=xml 고유한 헤더를 설정할 수 있는 비 브라우저 클라이언트를 사용할 때 예상되는 다른 동작을 방해하지 않습니다.


mdisibio

WebApiConfig 클래스에 두 줄의 코드를 추가하기만 하면 됩니다.

 public static class WebApiConfig { public static void Register(HttpConfiguration config) { //add this two line config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); ............................ } }

Md. Sabbir Ahamed

다음과 같이 App_Start/WebApiConfig.cs 변경하면 됩니다.

 public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); //Below formatter is used for returning the Json result. var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); //Default route config.Routes.MapHttpRoute( name: "ApiControllerOnly", routeTemplate: "api/{controller}" ); }

vaheeds

MSDN 에서 ASP.NET 및 AngularJS를 사용하여 단일 페이지 응용 프로그램 만들기 (약 41분).

 public static class WebApiConfig { public static void Register(HttpConfiguration config) { // ... possible routing etc. // Setup to return json and camelcase it! var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); }

최신 상태여야 하고 시도했고 효과가 있었습니다.


lko

이 질문이 요청되고 답변된 이후로 시간이 좀 지났지만 또 다른 옵션은 아래와 같이 MessageHandler를 사용하여 요청을 처리하는 동안 서버의 Accept 헤더를 재정의하는 것입니다.

 public class ForceableContentTypeDelegationHandler : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var someOtherCondition = false; var accHeader = request.Headers.GetValues("Accept").FirstOrDefault(); if (someOtherCondition && accHeader.Contains("application/xml")) { request.Headers.Remove("Accept"); request.Headers.Add("Accept", "application/json"); } return await base.SendAsync(request, cancellationToken); } }

여기서 someOtherCondition 은 브라우저 유형 등을 포함한 모든 것이 될 수 있습니다. 이것은 때때로 기본 콘텐츠 협상을 재정의하려는 조건부 경우에 해당합니다. 그렇지 않으면 다른 답변에 따라 구성에서 불필요한 포맷터를 제거하기만 하면 됩니다.

당연히 등록을 해야 합니다. 다음 중 하나를 전역적으로 수행할 수 있습니다.

 public static void Register(HttpConfiguration config) { config.MessageHandlers.Add(new ForceableContentTypeDelegationHandler()); }

또는 경로별 경로:

 config.Routes.MapHttpRoute( name: "SpecialContentRoute", routeTemplate: "api/someUrlThatNeedsSpecialTreatment/{id}", defaults: new { controller = "SpecialTreatment" id = RouteParameter.Optional }, constraints: null, handler: new ForceableContentTypeDelegationHandler() );

HttpModule 처럼 파이프라인의 요청 및 응답 끝에서 모두 실행됩니다. 따라서 사용자 정의 헤더로 재정의를 쉽게 확인할 수 있습니다.

 public class ForceableContentTypeDelegationHandler : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var wasForced = false; var someOtherCondition = false; var accHeader = request.Headers.GetValues("Accept").FirstOrDefault(); if (someOtherCondition && accHeader.Contains("application/xml")) { request.Headers.Remove("Accept"); request.Headers.Add("Accept", "application/json"); wasForced = true; } var response = await base.SendAsync(request, cancellationToken); if (wasForced){ response.Headers.Add("X-ForcedContent", "We overrode your content prefs, sorry"); } return response; } }

rism

다음은 내 응용 프로그램에서 사용한 가장 쉬운 방법입니다. Register 함수의 App_Start\\WebApiConfig.cs 에 아래 3줄의 코드를 추가합니다.

 var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.XmlFormatter); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

Asp.net 웹 API는 반환 개체를 JSON으로 자동 직렬화하고 application/json 이 헤더에 추가되면 브라우저나 수신자가 JSON 결과를 반환한다는 것을 이해할 수 있습니다.


Vikas Bansal

수년간 Felipe Leusin 의 답변을 사용하여 핵심 라이브러리와 Json.Net의 최근 업데이트 후 System.MissingMethodException :SupportedMediaTypes가 발생했습니다. 내 경우에는 동일한 예기치 않은 예외가 발생하는 다른 사람들에게 도움이 되기를 바라며 System.Net.Http 를 설치하는 솔루션입니다. NuGet은 어떤 상황에서는 분명히 제거합니다. 수동 설치 후 문제가 해결되었습니다.


Charles Burns

WebApiConfig는 json으로 출력할지 xml로 출력할지 설정할 수 있는 곳입니다. 기본적으로 xml입니다. 등록 기능에서 HttpConfiguration 포맷터를 사용하여 출력 형식을 지정할 수 있습니다.

System.Net.Http.Headers => MediaTypeHeaderValue("text/html") 는 json 형식의 출력을 가져오는 데 필요합니다.

여기에 이미지 설명 입력


rocky_pps

한 번만 설치하면 모든 API(자체 또는 타사)에 사용할 수 있는 적절한 도구를 사용하는 대신 하나의 API에서 단일 사용 사례(GET)를 변경하기 위해 코딩이 필요한 답변이 너무 많아서 놀랐습니다. 사용 사례.

따라서 좋은 대답은 다음과 같습니다.

  1. json 또는 기타 컨텐츠 유형만 요청하려면 Requestly 또는 유사한 도구를 설치하고 Accept 헤더를 수정하십시오.
  2. POST도 사용하고 json, xml 등의 형식이 잘 지정된 경우 Postman 또는 ARC 와 같은 적절한 API 테스트 확장을 사용하십시오.

user3285954

출처 : http:www.stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome

반응형