프런트 엔드 ASP.NET MVC4를 하나의 프로젝트로, ASP.NET Web API를 동일한 솔루션의 다른 프로젝트로-프런트 엔드에서 WebAPI를 호출하는 방법은 무엇입니까?

마이크 마크스

내 솔루션에 하나의 프로젝트로 ASP.NET MVC4 프런트 엔드가 있고 동일한 솔루션의 다른 프로젝트로 별도의 ASP.NET Web API가 있습니다. Web API에는 내 모든 CRUD 작업이 포함됩니다.

2 개의 질문

  1. CRUD 작업을 수행하기 위해 프런트 엔드에서 웹 API를 어떻게 호출합니까? 내 웹 API 프로젝트에 엔터티 데이터 모델이 정의되어 있고 프런트 엔드 뷰를 바인딩해야합니다. 어떻게해야합니까?
  2. 이것이 내 웹 서버에 배포되면 프런트 엔드는 한 서버에 상주하고 웹 API는 다른 서버 (대부분의 웹 서비스를 보유하는 서버)에 상주합니다. 따라서 동일한 라인을 따라 배포 한 후 프런트 엔드에서 웹 API를 어떻게 호출할까요? Web API가 단순히 HTTP 요청으로 호출된다는 것을 이해하지만 내 모델 (내 Web API 프로젝트에 정의 됨)을 내 뷰 (내 프런트 엔드 프로젝트)에 전달하는 측면에서 어떻게해야합니까?
마이크 마크스

Kevin이 옳지 만 나는 이것을 Ajax가 아닌 방식으로 수행했습니다. 저는 JSON 데이터로 작업하고 있으므로 JSON을 중심으로합니다.

컨트롤러 페이지에서 DbContext, Entity Framework 등과 관련된 모든 것을 제거합니다. 이유는 기본적으로 컨트롤러가 DbContext를 호출하여 CRUD 작업을 수행하기를 원하기 때문입니다. 대신 WebAPI를 호출하려고합니다.

가장 먼저 컨트롤러에서 일부 멤버 변수를 선언하십시오. 나머지 컨트롤러는 다음을 활용합니다.

    HttpClient client = new HttpClient();
    HttpResponseMessage response = new HttpResponseMessage();
    Uri contactUri = null;
  1. 컨트롤러에서 다음과 같이 컨트롤러에 대한 생성자를 만듭니다.

    public ContactController()
    {
        // set base address of WebAPI depending on your current environment
        client.BaseAddress = new Uri("http://server/YourAPI/");
    
        // Add an Accept header for JSON format.
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }
    
  2. Index 작업의 코드를 다음과 같이 바꿉니다. 유일한 관련 부분은 client.GetAsync()부름과 var contacts할당입니다. 이 문제의 맥락에서 다른 모든 것은 필요하지 않습니다. 내부의 값 client.GetAsync()은 컨트롤러의 이름이어야하며 WebApiConfig.cs에서 설정 한 사용자 지정 라우팅이 앞에 추가되어야합니다. 제 경우에는 apiAPI 호출과 일반 호출을 구분하기 위해 내 경로에 부분을 추가했습니다 .

    public ActionResult Index()
    {
        response = client.GetAsync("api/contact").Result;
        if (response.IsSuccessStatusCode)
        {
            var contacts = response.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
            return View(contacts);
        }
        else
        {
            // add something here to tell the user hey, something went wrong
            return RedirectToAction("Index");
        }
    }
    
  3. Create 작업 (HttpPost 작업)을 다음과 같이 바꿉니다. 다시 말하지만, 유일한 중요한 부분은 client.PostAsJsonAsync()부분입니다. 이것은 제 경우에는 데이터베이스에 새 레코드를 삽입하는 작업을 처리하는 WebAPI의 POST 작업을 호출하는 것입니다.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Contact contact)
    {
        // Create a new product
        response = client.PostAsJsonAsync("api/contact", contact).Result;
        if (response.IsSuccessStatusCode)
        {
            return RedirectToAction("Index");
        }
        else
        {
            // add something here to tell the user hey, something went wrong
            return RedirectToAction("Index");
        }
    }
    
  4. 편집 작업 (비 HttpPost 작업)을 다음과 같이 바꿉니다. 편집하려면 먼저 레코드를 검색해야했기 때문에 약간 까다로 웠습니다. 따라서 기본적으로 Edit의 HttpPost 버전에는 편집 POST (PUT)를 수행하는 추가 코드 줄과 함께 다소 유사한 코드가 포함됩니다. 아래에서는 특정 레코드 ID를 전달하여 WebAPI에서 응답을받습니다. 따라서 인덱스 (GET)와 마찬가지로 ID 만 전달하여 동일한 작업을 수행하므로 하나의 레코드 만 반환됩니다. 그런 다음 View에서 작동 할 수있는 실제 개체에 대한 응답을 캐스팅합니다.

    public ActionResult Edit(int id = 0)
    {
        response = client.GetAsync(string.Format("api/contact/{0}", id)).Result;
        Contact contact = response.Content.ReadAsAsync<Contact>().Result;
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }
    
  5. Replace the Edit action (the HttpPost action) with something like the following. Below, we're getting the record to be edited by calling client.GetAsync() and passing in the primary key as a parameter (contact_id). Then, we're getting the RequestUri from that response and saving it. Then, we're calling client.PutAsJsonAsync() and passing in the Uri.PathAndQuery (what we just saved) as well as the object to be edited.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Contact contact)
    {
        response = client.GetAsync(string.Format("api/contact/{0}", contact.contact_id)).Result;
        contactUri = response.RequestMessage.RequestUri;
        response = client.PutAsJsonAsync(contactUri.PathAndQuery, contact).Result;
        if (response.IsSuccessStatusCode)
        {
            return RedirectToAction("Index");
        }
        else
        {
            // add something here to tell the user hey, something went wrong
            return RedirectToAction("Index");
        }
    }
    
  6. Replace the Delete action (the non-HttpPost action) with something like the following. So again, we're getting the record from the database by simply calling client.GetAsync() and casting it to an actual object my app knows of.

    public ActionResult Delete(int id = 0)
    {
        response = client.GetAsync(string.Format("api/contact/{0}", id)).Result;
        Contact contact = response.Content.ReadAsAsync<Contact>().Result;
    
        if (contact == null)
        {
            return HttpNotFound();
        }
        return View(contact);
    }
    
  7. 마지막으로 삭제 작업 (HttpPost 작업)을 다음과 같이 바꿉니다. 다시 말하지만, 우리는 편집 작업과 비슷한 작업을하고 있습니다. client.DeleteAsync()아래에 표시된 것처럼 삭제할 레코드를 가져 와서 객체로 캐스팅 한 다음 해당 객체를 호출에 전달 합니다.

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        response = client.GetAsync(string.Format("api/contact/{0}", id)).Result;
        contactUri = response.RequestMessage.RequestUri;
        response = client.DeleteAsync(contactUri).Result;
        return RedirectToAction("Index");
    }
    

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관