2010-10-27 188 views
2

我創建了一個ASP.NET MVC視圖。在我的MVC WebApp上,它效果很好。幫助從控制檯呈現ASP.NET MVC視圖應用程序

我希望能夠(從控制檯應用程序)將視圖呈現爲HTML電子郵件。我想知道做這件事的最好方法是什麼,我正在努力的部分是呈現視圖。

有沒有辦法從控制檯應用程序做到這一點?

該webapp只是簡單地調用Web服務並很好地格式化數據,以便控制檯應用程序可以訪問相同的Web服務;但是,控制器上的ActionResult受到[Authorize]屬性的保護,因此不僅僅是任何人都可以得到它。

+0

是一個挑戰渲染或授權? – Aliostad 2010-10-27 15:48:57

+0

要麼 - 如果我必須使用WebRequest,那麼授權將是我的問題,因爲我不能只發送憑據,我可以嗎?如果有更好的方式,比如添加對我的mvc-app的引用,那麼渲染就是問題所在。長話短說,我不確定從哪裏開始。 – Nate 2010-10-27 15:51:05

回答

0

我結束了使用HttpWebRequest和這裏提供的信息:http://odetocode.com/articles/162.aspx

從文章:

// first, request the login form to get the viewstate value 
    HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;   
    StreamReader responseReader = new StreamReader(
     webRequest.GetResponse().GetResponseStream() 
    ); 
    string responseData = responseReader.ReadToEnd();   
    responseReader.Close(); 

    // extract the viewstate value and build out POST data 
    string viewState = ExtractViewState(responseData);  
    string postData = 
     String.Format(
      "__VIEWSTATE={0}&UsernameTextBox={1}&PasswordTextBox={2}&LoginButton=Login", 
      viewState, USERNAME, PASSWORD 
     ); 

    // have a cookie container ready to receive the forms auth cookie 
    CookieContainer cookies = new CookieContainer(); 

    // now post to the login form 
    webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest; 
    webRequest.Method = "POST"; 
    webRequest.ContentType = "application/x-www-form-urlencoded"; 
    webRequest.CookieContainer = cookies;   

    // write the form values into the request message 
    StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()); 
    requestWriter.Write(postData); 
    requestWriter.Close(); 

    // we don't need the contents of the response, just the cookie it issues 
    webRequest.GetResponse().Close(); 

    // now we can send out cookie along with a request for the protected page 
    webRequest = WebRequest.Create(SECRET_PAGE_URL) as HttpWebRequest; 
    webRequest.CookieContainer = cookies; 
    responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); 

    // and read the response 
    responseData = responseReader.ReadToEnd(); 
    responseReader.Close(); 

    Response.Write(responseData); 
2

是的,你可以。我假設你正在使用表單身份驗證。只需進行身份驗證,即可獲取會話頭Cookie並將其複製到新的Web請求中。

+0

我從來沒有這樣做過,有沒有這樣做的資源?我只需在我的WebRequest類中添加一個'NetworkCredentials'? – Nate 2010-10-27 16:03:57

+0

僅當您使用Windows身份驗證時。 – Aliostad 2010-10-27 16:05:02

+0

我正在使用表單身份驗證。在ActionResult上有一個簡單的[Authorize]屬性... – Nate 2010-10-27 16:15:30