代码之家  ›  专栏  ›  技术社区  ›  Nate CSS Guy

帮助从控制台应用程序呈现ASP.NET MVC视图

  •  2
  • Nate CSS Guy  · 技术社区  · 14 年前

    我已经创建了一个ASP.NET MVC视图。在我的MVC WebApp上,它工作得很好。

    有没有什么方法可以从控制台应用程序中执行此操作?

    webapp只需调用一个web服务并对数据进行良好的格式化,这样控制台应用程序就可以访问同一个web服务;但是,控制器上的ActionResult受[授权]属性保护,因此不只是任何人都可以访问它。

    2 回复  |  直到 14 年前
        1
  •  2
  •   Aliostad    14 年前

    是的,你可以。我猜你在使用表单身份验证。只需验证,获取会话头cookie并将其复制到新的web请求。

        2
  •  0
  •   Nate CSS Guy    14 年前

    我最终使用了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);