2014-01-10 2 views
0
내 솔루션에서

ASP.NET 웹 API와 작업 : 난 내 모델 클래스와 (첫 번째 코드) 단일 dbcontext이이 프로젝트에서유효성 내가 세 가지 프로젝트가

App.Model

public class Customer 
{ 
    [Key] 
    public int ID { get; set; } 

    public string Name { get; set; } 
} 

App.UI - MVC 프로젝트 여기

, 컨트롤러가 의 (방법을 가져 오기) 및 뷰

public ActionResult Create() 
    { 
     return View(); 
    } 

App.Validation

- ASP.NET 웹 API 프로젝트

여기 검증 (Post 메소드) 전용 컨트롤러가 있습니다.

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create([Bind(Include="ID,Name")] Customer customer) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Customer.Add(customer); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(customer); 
    } 

UI 프로젝트의 컨트롤러에서 게시 작업을 호출하면 API 프로젝트의 컨트롤러가 UI 컨트롤러의 유효성 검사를 수행합니다.

RouteConfig 및 WebApiConfig에서 라우팅 규칙을 변경해야하며 그렇지 않으면 API에 매개 변수로 동작을 전달해야합니까?

+0

당신이 asp.net 웹 API를 응용 프로그램에 전달하려고하는 모델의 샘플이 있습니까? –

+0

내 질문을 수정했습니다. – Mirko

답변

1

이렇게하는 한 가지 방법은 UI 컨트롤러 동작에서 API 컨트롤러 동작을 호출하는 것입니다.

[HttpPost] 
    public ActionResult Create(Customer customer) 
    { 
     try 
     { 
      var json = JsonConvert.SerializeObject(customer); 
      Encoding encoding = Encoding.UTF8; 

      var requestBody = encoding.GetBytes(json) 
      var uri = ""; // replace empty string with the uri of the web Api project 

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
      request.Timeout = 999; 
      request.ContentType = "application/json"; 
      request.Method = "put"; 
      request.ContentLength = requestBody.Length; 
      request.GetRequestStream().Write(requestBody, 0, requestBody.Length); 
      request.GetResponse(); 

      return RedirectToAction("Index"); 
     } 
     catch (WebException e) 
     { 
      // handle exception 
      return View(customer); 
     } 
    } 

웹 API 액션이 같은 수 있습니다 :

[HttpPost] 
public HttpResponseMessage Create(Customer customer) 
{ 
    if (ModelState.IsValid) 
    { 
     db.Customer.Add(customer); 
     db.SaveChanges(); 
     return Request.CreateResponse(HttpStatusCode.OK); 
    }   
    else 
    { 
     return Request.CreateErrorResponse(HttpStatusCode.BadRequest); 
    } 
} 
+0

웹 API 프로젝트의 URI입니다. 조치 URL을 의미합니까? http : // localhost/api/Customer/Create? – Mirko

+0

@mike, 맞습니다. – Ronald

관련 문제