Json을 사용하여 Web API에서 응답을 직렬화하지 못했습니다.
ASP와 함께 일하고 있습니다.NET MVC 5 Web API모든 사용자와 상의하고 싶습니다.
나는 썼다api/users
다음과 같이 입력합니다.
"'ObjectContent'1' 유형이 콘텐츠 유형 'application/json; charset=utf-8'에 대한 응답 본문을 직렬화하지 못했습니다."
WebApiConfig에서 이미 다음 행을 추가했습니다.
HttpConfiguration config = new HttpConfiguration();
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
하지만 여전히 작동되지 않습니다.
데이터를 반환하는 기능은 다음과 같습니다.
public IEnumerable<User> GetAll()
{
using (Database db = new Database())
{
return db.Users.ToList();
}
}
EF와 함께 작업하는 경우 Global.asax에 아래 코드를 추가하는 것 외에
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
Import 잊지 마세요
using System.Data.Entity;
그런 다음 자체 EF 모델을 반환할 수 있습니다.
그렇게 간단해!
Web API(또는 다른 웹 서비스)에서 소비자에게 데이터를 반환할 때는 데이터베이스에서 가져온 엔티티를 반환하지 않는 것이 좋습니다.데이터베이스가 아닌 데이터 모양을 제어할 수 있는 모델을 사용하는 것이 훨씬 더 안정적이고 유지 보수 가능합니다.이렇게 하면 WebApiConfig에서 포메터를 너무 많이 조작할 필요가 없습니다.하위 모델이 속성으로 있는 UserModel을 생성하고 반환 개체에서 참조 루프를 제거할 수 있습니다.그러면 연재기가 훨씬 더 행복해질 거예요.
또한 요청에 "Accepts" 머리글만 지정하는 경우에는 일반적으로 포맷터나 지원되는 미디어 유형을 제거할 필요가 없습니다.그런 것들을 가지고 놀면 가끔 더 혼란스러울 수 있어요.
예:
public class UserModel {
public string Name {get;set;}
public string Age {get;set;}
// Other properties here that do not reference another UserModel class.
}
정답을 지정하는 것도 하나의 방법이지만, 1개의 설정만으로 수정할 수 있는 경우는 과잉입니다.
dbcontext 컨스트럭터에서 사용하는 것이 좋습니다.
public DbContext() // dbcontext constructor
: base("name=ConnectionStringNameFromWebConfig")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
를 에 추가합니다.global.asax
을 on on on의 Application_Start
:
신원에서 .Ignore
로로 합니다..Serialize
효과가 있을 거야
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
public class UserController : ApiController
{
Database db = new Database();
// construction
public UserController()
{
// Add the following code
// problem will be solved
db.Configuration.ProxyCreationEnabled = false;
}
public IEnumerable<User> GetAll()
{
return db.Users.ToList();
}
}
WebApiConfig.cs 파일의 이 코드를 사용하여 해결했습니다.
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
이 코드가 마음에 들지 않습니다.
foreach(var user in db.Users)
대신 다음과 같은 작업을 수행할 수 있습니다. 이 작업은 저에게 효과가 있었습니다.
var listOfUsers = db.Users.Select(r => new UserModel
{
userModel.FirstName = r.FirstName;
userModel.LastName = r.LastName;
});
return listOfUsers.ToList();
하지만 결국 루카스 로젤리의 솔루션을 사용하게 되었습니다.
업데이트: 익명 개체를 반환하여 단순화:
var listOfUsers = db.Users.Select(r => new
{
FirstName = r.FirstName;
LastName = r.LastName;
});
return listOfUsers.ToList();
을 에에 your 에 추가하다Application_Start()
의 of의 Global.asax
합니다.
protected void Application_Start()
{
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
// ...
}
2: [않음]2: [권장하지 않음]
Entity Framework 를 、 DbContext entity entity entity entity entity 。메모모델을 하면 이 코드가 됩니다.
public class MyDbContext : DbContext
{
public MyDbContext()
{
this.Configuration.ProxyCreationEnabled = false;
}
}
또, 같은 에러가 발생하는 시나리오도 있습니다.
이 환田음인 List<dynamic>
메서드 API to
예:
public HttpResponseMessage Get()
{
var item = new List<dynamic> { new TestClass { Name = "Ale", Age = 30 } };
return Request.CreateResponse(HttpStatusCode.OK, item);
}
public class TestClass
{
public string Name { get; set; }
public int Age { get; set; }
}
따라서 이 시나리오에서는 다음과 같이 반환 클래스(모두)에서 [KnownTypeAttribute]를 사용합니다.
[KnownTypeAttribute(typeof(TestClass))]
public class TestClass
{
public string Name { get; set; }
public int Age { get; set; }
}
이거면 돼!
아래 만 더하면 .App_Start/WebApiConfig.cs
그러면 기본적으로 XML 대신 json이 반환되고 오류가 발생하지 않습니다." 편집 불필요"Global.asax
XmlFormatter
타 etc기?
'ObjectContent'1' 유형이 콘텐츠 유형 'application/xml; charset=utf-8'에 대한 응답 본문을 직렬화하지 못했습니다.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
global.asax에 다음 행을 입력합니다.
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
수입품
using System.Data.Entity;
자동 매핑 사용...
public IEnumerable<User> GetAll()
{
using (Database db = new Database())
{
var users = AutoMapper.Mapper.DynamicMap<List<User>>(db.Users);
return users;
}
}
다음 네임스페이스를 사용합니다.
using System.Web.OData;
대신:
using System.Web.Http.OData;
그것은 나에게 효과가 있었다.
아래 행을 추가합니다.
this.Configuration.ProxyCreationEnabled = false;
Two way to use 2가지 사용방법ProxyCreationEnabled
as ~하듯이false
.
에 가 하 add
DBContext
건설 또는 스)public ProductEntities() : base("name=ProductEntities") { this.Configuration.ProxyCreationEnabled = false; }
또는
Add the line inside of 안에 행을 추가합니다.
Get
방법public IEnumerable<Brand_Details> Get() { using (ProductEntities obj = new ProductEntities()) { this.Configuration.ProxyCreationEnabled = false; return obj.Brand_Details.ToList(); } }
클래스에 [Serializable](시리얼화 가능
예:
[Serializable]
public class UserModel {
public string Name {get;set;}
public string Age {get;set;}
}
나한텐 효과가 있었어!
효과적인 솔루션:
Use 사용하다
[DataContract]
및 class수용[DataMember]
시리얼화할 각 속성의 속성.이 정도면 Json 결과를 얻을 수 있습니다(예: 피들러로부터).을 가져오려면 xml로 .
Global.asax
음음음:var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; xml.UseXmlSerializer = true;
- 이 기사를 읽어주세요.시리얼라이제이션에 대해 이해하는 데 도움이 되었습니다.https://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization
jensendp의 답변에 추가하려면:
사용자 생성 모델에 엔티티를 전달하고 해당 엔티티의 값을 사용하여 새로 생성된 모델의 값을 설정합니다.예를 들어 다음과 같습니다.
public class UserInformation {
public string Name { get; set; }
public int Age { get; set; }
public UserInformation(UserEntity user) {
this.Name = user.name;
this.Age = user.age;
}
}
다음 ''로 바꿔주세요IEnumerable<UserInformation>
위의 답변은 모두 맞지만 [InnerException]> [ Exception Message ]를 체크하는 것이 좋습니다.
"ObjectContext 인스턴스가 삭제되어 연결이 필요한 작업에 더 이상 사용할 수 없습니다."와 같은 메시지가 표시될 경우.이는 EF의 디폴트 동작 때문에 문제가 될 수 있습니다.
DbContext 생성자에 LazyLoadingEnabled = false를 할당하면 문제가 해결됩니다.
public class MyDbContext : DbContext
{
public MyDbContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}
EF의 EagerLoading 및 LazyLoading 동작에 대한 자세한 내용은 이 MSDN 문서를 참조하십시오.
내 경우 다음과 같은 오류 메시지가 나타납니다.
'ObjectContent'1' 유형이 콘텐츠 유형 'application/xml; charset=utf-8'에 대한 응답 본문을 직렬화하지 못했습니다.
하지만 자세히 살펴보니 문제는 다음과 같습니다.
name 이라고 입력합니다.데이터 계약 이름이 'SomeSubRootType://schemas.datacontract.org/2004/07/WhatEverService''인 일부 SubRootType은 예상되지 않습니다.DataContractSerializer를 사용하는 경우 또는 알려진 유형 목록에 정적으로 알려지지 않은 유형을 추가하는 경우(예: 알려진 유형 사용) DataContractResolver 사용을 고려하십시오.TypeAttribute Atribute Atribute Atribute를 사용하거나 시리얼라이저에 전달된 기존 유형 목록에 추가합니다.
by by by by by by by by by by by by by by by by를 추가하여 한 방법KnownType
.
[KnownType(typeof(SomeSubRootType))]
public partial class SomeRootStructureType
이것은 이 대답에서 영감을 얻어 해결되었다.
참고 자료: https://msdn.microsoft.com/en-us/library/ms730167(v=vs.100).aspx
기본적으로 한 줄을 추가합니다.
- 엔티티배열.ProxyCreationEnabled = false;
UsersController.cs 에 접속해 주세요.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using UserDataAccess;
namespace SBPMS.Controllers
{
public class UsersController : ApiController
{
public IEnumerable<User> Get() {
using (SBPMSystemEntities entities = new SBPMSystemEntities()) {
entities.Configuration.ProxyCreationEnabled = false;
return entities.Users.ToList();
}
}
public User Get(int id) {
using (SBPMSystemEntities entities = new SBPMSystemEntities()) {
entities.Configuration.ProxyCreationEnabled = false;
return entities.Users.FirstOrDefault(e => e.user_ID == id);
}
}
}
}
WebApiConfig.cs 내에서 App_Start 폴더에서 사용할 수 있는 시리얼라이저 포메터를 다음과 같이 정의해야 합니다.
설정을 추가하고 있습니다.포메터삭제(config)포메터XmlFormatter); // JSON 포맷으로 데이터를 제공합니다.
설정을 추가하고 있습니다.포메터삭제(config)포메터JsonFormatter); // XML 형식으로 데이터를 제공합니다.
이 오류가 발생한 또 다른 예는 데이터베이스 쿼리가 null 값을 반환했지만 사용자/뷰 모델 유형이 null 불가로 설정된 경우입니다.를 들어 ]필드를 [UserModel]에서하는 int
로로 합니다.int?
결했습습니니다
이 문제는 응답 유형이 공개되지 않은 경우에도 발생합니다.Visual Studio를 사용하여 유형을 생성했기 때문에 내부 클래스를 반환했습니다.
internal class --> public class
Visual Studio의 기본 형식은 "XmlFormat"(config)인 반면 Visual Studio 자체는 json 형식이어야 하므로 Visual Studio 2017 또는 2019는 전혀 고려하지 않습니다.포메터XmlFormatter).
Visual Studio는 개발자들에게 너무 많은 폐를 끼치지 말고 자동으로 이 작업을 수행해야 합니다.
이 문제를 해결하려면 WebApiConfig.cs 파일로 이동하여
var json = 설정.포메터Json Formatter; json.시리얼라이저 설정PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.오브젝트, 설정포메터삭제(config)포메터Xml Formatter);
"config" 뒤에 표시됩니다.MapHttpAttributeRoutes();"를 선택합니다.그러면 프로젝트에서 json 출력을 생성할 수 있습니다.
저 같은 경우에는 데이터베이스 재작성을 해결했습니다.모델을 변경하고 Package Manager Console에서 Update-Database를 실행하면 다음 오류가 나타납니다.
ALTER TABLE 문이 FORNE KEY 제약 조건인 FK_dbo와 충돌했습니다.액티비티_dbo.Project_ProjectId"를 참조해 주세요.데이터베이스 "TrackEmAllContext-20190530144302", 테이블 "dbo"에서 충돌이 발생했습니다.프로젝트", 'Id' 열.
다음과 같은 경우:WebApiConfig.cs 또는 Global.asax.cs에 코드를 추가해도 문제가 없는 경우:
.ToList();
.ToList() 함수를 추가합니다.
모든 솔루션을 시도해 보았지만, 다음과 같은 방법이 효과가 있었습니다.
var allShops = context.shops.Where(s => s.city_id == id)**.ToList()**;
return allShops;
도움이 됐으면 좋겠어요.
내 경우 내비게이션 속성 전에 virtual 키워드를 삭제했을 때 수정되었습니다.즉, 참조 테이블입니다.그래서 바꿨어요.
public virtual MembershipType MembershipType { get; set; }
대상:
public MembershipType MembershipType { get; set; }
언급URL : https://stackoverflow.com/questions/23098191/failed-to-serialize-the-response-in-web-api-with-json
'programing' 카테고리의 다른 글
".bat" 파일에서 명령줄 매개 변수를 확인하는 방법 (0) | 2023.04.08 |
---|---|
Angularjs 세션스토리지 및 범위 (0) | 2023.03.30 |
JSON을 CSV 형식으로 변환하고 변수에 저장하는 방법 (0) | 2023.03.29 |
WooCommerce의 국가 코드에서 국가 이름을 가져오는 중 (0) | 2023.03.29 |
WordPress Gutenberg 블록:페이지 수준 블록을 제한하지만 모든 하위 수준 블록을 허용하는 방법 (0) | 2023.03.29 |