program story

Webapi에 ViewModel을 포함하는 것이 합리적입니까?

inputbox 2020. 11. 25. 07:56
반응형

Webapi에 ViewModel을 포함하는 것이 합리적입니까?


나는 webapi를 배우기 시작했고 MVC 프로젝트에서는 의미가 있지만 의미가 없을 수도있는 일을하고 있다는 것을 알게되었습니다.

일반적으로 MVC 프로젝트에서 ViewModels를 만들고 매개 변수로 사용하거나 뷰와 함께 다시 전달합니다.

webapi에는 뷰가 없기 때문에 ViewModel을 매개 변수로 사용하는 것은 의미가 없다고 생각합니다.

매개 변수로 내 EF 도메인 (코드 우선)을 가져야하고 그 위에 데이터 주석을 추가해야하는지 궁금합니다. 나는 일반적으로 도메인에서 이것을 좋아하는 것처럼 뷰 모델 속성에 주석을 넣었습니다.

그러나 이것을 막는 것은 내 MVC 사이트가 어떻게 작동하는지 100 % 명확하지 않다는 것입니다.

MVC 사이트가 단순 뷰를 뱉어 낸 다음 Jquery를 사용하여 webapi를 호출합니까 아니면 Webapi가 호출하는 것과 동일한 메서드를 직접 호출하는 MVC 작업 메서드를 호출합니까?

두 번째 방법이라면 데이터 주석을 내 뷰 모델에 다시 넣었지만 EF 도메인과 VM 모두에 동일한 주석을 배치하고 중복되는 것 같습니다.


용어를 제쳐두고 바인딩을위한 모델을 갖는 것은 여전히 ​​사용 중입니다. 그것들은 기술적으로 더 이상 ViewModels가 아닙니다. 그러나 그들은 여전히 ​​사용 중입니다. 이를 사용하면 모델 속성의 속성을 활용하고 필요한 경우 API 전체에서 속성을 재사용 할 수 있습니다. 또한 엔티티를 직접 사용하는 경우 WebAPI는 의도하지 않았더라도 이름으로 일치하는 모든 매개 변수를 모델로 바인딩합니다.

또한 엔터티 모델은 원시 데이터의 표현이지만 바인딩에 사용되는 모델은 API 요청이 요청을 성공적으로 처리하기 위해 충족해야하는 고정 계약입니다. 구현이 완료 될 때까지 여러 엔터티 모델에 걸쳐있는 값이 데이터 저장소에 전혀 유지되지 않을 수 있습니다.


'물건' 으로 작업 한 후 내 제안 :

데이터 바인딩을위한 BindingModels (mvc 또는 api)

mvc의 뷰에 대한 ViewModels (API 내부에 mvc 페이지가있을 수 있으므로이를위한 장소가있는 것이 좋습니다. 문서, 소개 페이지 등이 될 수 있습니다. 뷰가없는 경우 ViewModels가 없을 수 있습니다.) 이것의 장점은 Views / web.config에서 ViewModels 네임 스페이스 참조를 가질 수 있으며 API 리소스로 오염되지 않는다는 것입니다.

웹 API 리소스 용 ResourceModel 입니다. webapi에서 중첩 된 리소스는 mvc에서 흔하지 않은 트리의 어느 곳으로나 이동하는 리소스이기도하므로 리소스 이름을 지정하는 것이 좋습니다.

자원을 받으려면 자원 모델을 사용할 수 있습니다. 당신이 다시 보내는 것과 같은 것을 받고 있다는 것을 기억하십시오.

입력에 대한 사용자 지정 바인딩을 원하는 경우 (기본 시나리오 여야 함) 바인딩 모델이 있습니다.

mvc보기가있는 경우 관리 목적, 문서 등 무엇이든 ViewModels를 사용하십시오.

mvc에 양식 페이지가있는 경우 POST 컨트롤러에서도 BindingModel을 사용할 수 있습니다. MVC 또는 WEBAPI의 게시물에 대해 다른 모델을 가질 필요가 없습니다. 특히 모델 바인더 또는 포맷터가 동일한 데이터 주석을 사용하여 동일한 바인딩 모델을 이해하고 매핑 할 수있는 경우.

때로는 리소스와 일부 추가 필드가있는 바인딩 모델을 만들고 싶을 수 있습니다. 상속은 당신의 친구입니다.

두 개 이상의 리소스와 (선택적으로 추가 필드) 리소스를 사용하여 바인딩 모델을 만들고 싶을 때가 있습니다.

MVC 세계에서는 '자원'개념을 사용할 수도 있지만 훨씬 덜 일반적입니다. 동일한 프로젝트에 MVC와 Web Api가있을 때 유용합니다.

항목 (예 : 폴더 구조, 네임 스페이스 등)에 대한 추가 의견이 필요하면 알려주세요. 저는 제 단점 프로 경험을 공유하게되어 기쁩니다.

아, 그리고 잊었습니다. 매핑 전략은 조사 할 가치가 있습니다. 나는 개인적으로 내 자신의 매핑을 수행하지만이 논리 를 한 곳에 두는 것은 귀중합니다.

편집 : 아주 순진한 예

ContactViewModel{

    string Name {get;}
    string LastName {get;}
    List<Country> AvailableCountries {get;}
    Country Country {get;}
    bool IsAdmin {get;}

}

ContactBindingModel{

    string Name {get;set;}
    string LastName {get;set;}
    int Country {get;set;}

}

ContactResourceModel{

    string Name { get;set;}
    string LastName {get;set;}
    Country Country {get;set;}
    string IsAdmin {get;}

}

REST 기반 시스템을 구축하려는 경우 ViewModel 및 View 개념이 매우 유용 할 수 있습니다. Resource의 개념을 ViewModel에, 표현을 View에 상당히 가깝게 매핑 할 수 있습니다.

If you stop to think for a moment about what a view looks like in an MVC site. It's a HTML document. A document that contains a bunch of semantic information, title, body, sections, paragraphs, tables, etc. It's not supposed to contain "style" information. That's the job of the web browser and CSS. People get confused when they start to think of HTML as UI. It's not supposed to be UI, it is the content of the UI.

Views are just a concrete realization of the view model content using some media type that can be transferred over the wire. What that media type is, depends on what client you are trying to satisfy.


We are currently working on a similar project that uses ASP.Net MVC and ASP.Net Web Api.

We use ASP.Net MVC to generate the global structure of our pages. Then, our MVVM javascript implementation calls the web api to fill returned data in client view models. To do that, our api returns view model that correspond to what the front end is waiting for.

I think that your api view models would differ from MVC ViewModels (that are not ViewModels from a MVVM point of view).

It depends on your use of api too. For example, for an internal use, you don't always need to avoid to show your domain model. So you will avoid to map the Model in the ViewModel and increase performances. But in the case you need to transform some properties in your models, viewModels will greatly help you to structure your code in a loosely coupled way.

Since there are no views in webapi I guess it does not make sense to have a ViewModel as parameter.

I would say your api is consumed by your views in the end, it makes sense to have ViewModel.

Does the MVC site just spit back simples views and then you use Jquery to call your webapi or do you just call MVC action methods that directly just call the same methods the Webapi would call?

It is just a question of choice here. You can call MVC action to receive generated views (in html) or you can call WebApi to receive JSON/XML responses that you will then bind with your javascript code in your views.


Just to add what others have said, the use of what would normally be termed a ViewModel is useful for validation as well. You can mark up your classes with data annotations including any validation requirements. In your controller actions you can still use ModelState to force the validation to occur and return appropriate messages via HttpRequestException or just HttpResponseMessage.

참고URL : https://stackoverflow.com/questions/16365773/does-it-make-sense-to-have-viewmodels-in-the-webapi

반응형