programing

웹 API를 사용하여 익명 유형 반환

instargram 2023. 3. 28. 21:13
반응형

웹 API를 사용하여 익명 유형 반환

MVC를 사용하면 애드혹 Json을 쉽게 반환할 수 있습니다.

return Json(new { Message = "Hello"});

새로운 웹 API에서 이 기능을 찾고 있습니다.

public HttpResponseMessage<object> Test()
{    
   return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}

이 때문에, 이 예외는,DataContractJsonSerializer익명 유형을 처리할 수 없습니다.

이것을 Json 기반의 JsonNetFormatter로 대체했습니다.넷. 이 기능을 사용하려면

 public object Test()
 {
    return new { Message = "Hello" };
 }

하지만 돌아오지 않는다면 웹 API를 사용하는 것은 의미가 없습니다.HttpResponseMessage바닐라 MVC를 계속 사용하는 것이 좋을 것 같습니다.사용하려고 하면:

public HttpResponseMessage<object> Test()
{
   return new HttpResponseMessage<object>(new { Message = "Hello" }, HttpStatusCode.OK);
}

전체를 연재합니다.HttpResponseMessage.

어떤 사람이 익명의 유형을 반환할 수 있는 솔루션을 안내해 주실 수 있습니까?HttpResponseMessage?

이것은 베타 릴리스에서는 동작하지 않지만, 최신 비트(http://aspnetwebstack.codeplex.com에서 빌드)에서는 동작하기 때문에 RC에서는 동작할 수 있습니다.할수있습니다

public HttpResponseMessage Get()
{
    return this.Request.CreateResponse(
        HttpStatusCode.OK,
        new { Message = "Hello", Value = 123 });
}

이 답변은 조금 늦어질 수 있지만 오늘부로WebApi 2이미 출시되어 원하는 작업을 쉽게 수행할 수 있게 되었습니다.그냥 다음과 같이 하면 됩니다.

public object Message()
{
    return new { Message = "hello" };
}

그리고 파이프라인에 따라, 그것은 에 연재될 것이다.xml또는json고객의 기호에 따라Accept헤더)이게 이 질문에 부딪히는 사람에게 도움이 되길 바랍니다.

웹 API 2에서는 HttpResponseMessage를 대체하는 새로운 IHttpActionResult를 사용하여 간단한 Json 오브젝트(MVC와 유사)를 반환할 수 있습니다.

public IHttpActionResult GetJson()
    {
       return Json(new { Message = "Hello"});
    }

Json Object를 사용하여 다음을 수행할 수 있습니다.

dynamic json = new JsonObject();
json.Message = "Hello";
json.Value = 123;

return new HttpResponseMessage<JsonObject>(json);

Expando Object를 사용할 수 있습니다.(추가)

[Route("api/message")]
[HttpGet]
public object Message()
{
    dynamic expando = new ExpandoObject();
    expando.message = "Hello";
    expando.message2 = "World";
    return expando;
}

다음의 조작도 가능합니다.

var request = new HttpRequestMessage(HttpMethod.Post, "http://leojh.com");
var requestModel = new {User = "User", Password = "Password"};
request.Content = new ObjectContent(typeof(object), requestModel, new JsonMediaTypeFormatter());

ASP.NET Web API 2.1에서는 다음과 같이 간단한 방법으로 실행할 수 있습니다.

public dynamic Get(int id) 
{
     return new 
     { 
         Id = id,
         Name = "X"
     };
}

상세한 것에 대하여는, https://www.strathweb.com/2014/02/dynamic-action-return-web-api-2-1/ 를 참조해 주세요.

public IEnumerable<object> GetList()
{
    using (var context = new  DBContext())
    {
        return context.SPersonal.Select(m =>
            new  
            {
                FirstName= m.FirstName ,
                LastName = m.LastName
            }).Take(5).ToList();               
        }
    }
}

제네릭을 사용하면 익명 유형에 대한 "유형"이 제공되므로 이 기능을 사용할 수 있습니다.다음으로 시리얼라이저를 거기에 바인드 할 수 있습니다.

public HttpResponseMessage<T> MakeResponse(T object, HttpStatusCode code)
{
    return new HttpResponseMessage<T>(object, code);
}

없는 경우DataContract또는DataMebmer모든 공공재산을 직렬화하는 데 의존하게 되므로 원하는 대로 할 수 있습니다.

(오늘 늦게나 테스트 할 수 있을 것 같습니다만, 뭔가 문제가 있으면 알려 주세요.)

동적 개체를 다음과 같이 반환되는 개체로 캡슐화할 수 있습니다.

public class GenericResponse : BaseResponse
{
    public dynamic Data { get; set; }
}

WebAPI에서 다음과 같은 작업을 수행합니다.

[Route("api/MethodReturingDynamicData")]
[HttpPost]
public HttpResponseMessage MethodReturingDynamicData(RequestDTO request)
{
    HttpResponseMessage response;
    try
    {
        GenericResponse result = new GenericResponse();
        dynamic data = new ExpandoObject();
        data.Name = "Subodh";

        result.Data = data;// OR assign any dynamic data here;// 

        response = Request.CreateResponse<dynamic>(HttpStatusCode.OK, result);
    }
    catch (Exception ex)
    {
        ApplicationLogger.LogCompleteException(ex, "GetAllListMetadataForApp", "Post");
        HttpError myCustomError = new HttpError(ex.Message) { { "IsSuccess", false } };
        return Request.CreateErrorResponse(HttpStatusCode.OK, myCustomError);
    }
    return response;
}

언급URL : https://stackoverflow.com/questions/10123371/returning-anonymous-types-with-web-api

반응형