消费WCF休息4从ASP。净 [英] Consuming WCF Rest 4 From ASP . NET

查看:104
本文介绍了消费WCF休息4从ASP。净的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个完整的ASP .NET新手。我写了一组使用WCF 4休息入门套件Web服务。我把一切从一个Flash应用程序内,但我想写一个快速和肮脏的管理面板供自己使用有没有必要写在Flash中。

我想,这会更快得到这个和ASP中运行。所以,问题是考虑这样一个WCF功能:

  [WebInvoke(UriTemplate =/登录/方法=POST)]
        公共用户登录信息(用户用户)
        {
             // code在这里
             //要么抛出WebFaultException或会话ID返回用户登录

我怎么会消耗这从ASP净页面使用用户名,密码,提交盒,它要么显示错误401的等或成功(returneduser.sessionid)。

谢谢!

请注意:
我知道如何在C#中通过HTTP调用REST服务。这真的是有好办法,在ASP来,由于这个问题,或者它只是使格式如:

 < ASP:内容ID =内容2ContentPlaceHolderID =日程地址搜索Maincontent=服务器>
<形式的行动=WebForm2.aspx.cs>
    < ASP:文本框的id =电子邮件=服务器/>
    < ASP:文本框的id =密码=服务器/>
    < ASP:按钮的ID =Button1的的OnClick =OnButtonClick=服务器文本=登录/>
  < /表及GT;
  < ASP:标签ID =labelResult=服务器/>
< / ASP:内容>

然后在单击code背后做这样的事情:

 保护无效OnButtonClick(对象发件人,EventArgs的发送)
        {
            HttpWebRequest的REQ = WebRequest.Create(HTTP://本地主机:35810 /用户/登录/)作为HttpWebRequest的;            字符串userString = UsefulStuff.Serialization.SerializationUtil。
                SerializeDataContractToString(typeof运算(用户),新用户(){电子邮件=新的电子邮件(textboxUsername.text)
                                                                         密码=新密码(textboxPassword.text)});            字符串strResponse = GetHttpPostResponse(REQ,userString);            用户recievedUser = UsefulStuff.Serialization.SerializationUtil.DeserializeDataContractString(
                typeof运算(用户),strResponse)的用户;            labelResult.Text = recievedUser.SessionId;
        }
        公共静态字符串GetHttpPostResponse(HttpWebRequest的HttpWebRequest的,字符串serializedPayload)
        {
            httpWebRequest.Method =POST;
            httpWebRequest.ContentType =文/ XML;
            httpWebRequest.ContentLength = serializedPayload.Length;            StreamWriter的streamOut =新的StreamWriter(httpWebRequest.GetRequestStream(),Encoding.ASCII);
            streamOut.Write(serializedPayload);
            streamOut.Close();            StreamReader的streamIn =新的StreamReader(httpWebRequest.GetResponse()GetResponseStream());            字符串strResponse = streamIn.ReadToEnd();
            streamIn.Close();            返回strResponse;
        }


解决方案

基本方法来调用REST服务是HttpWebRequest的

序列化到XML

  //用户对象
数据的XElement =新的XElement(用户,
  新的XElement(用户名,用户名)
  新的XElement(密码,密码)
);MemoryStream的dataSream =新的MemoryStream();
data.Save(数据流);HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(YourServiceUrl);
request.Method =POST;
request.ContentType =application / xml进行;
//你需要知道的长度,它有你访问请求流前设置
request.ContentLength = dataStream.Length;使用(流requestStream = request.GetRequestStream())
{
  dataStream.CopyTo(requestStream);
  requestStream.Close();
}HttpWebResponse响应= request.GetResponse();
如果(response.Status ==的HTTPStatus code.Unauthorized)
{
  ...
}
其他
{
  ...
}
response.Close();

I am a complete ASP .NET newbie. I've written a set of web services using the WCF 4 Rest Starter Kit. I call everything from within a Flash application but I want to write a quick and dirty admin panel for myself to use which has no need to be written in Flash.

I figure it will be faster to get this up and running in ASP. So the question is consider a WCF function like this:

[WebInvoke(UriTemplate = "/Login/", Method = "POST")]
        public User Login(User user)
        {
             // Code here
             // Either throw a WebFaultException or return the logged in user with a session id

How would I consume this from an ASP .Net page with a username, password, submit box and it either displays errors 401's etc or success (returneduser.sessionid).

Thanks!

Note: I am aware of how to call a Rest service over Http in C#. It's really a question of is there a "nice way" to due this in ASP or is it just make a form like:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form action="WebForm2.aspx.cs" >
    <asp:textbox id="Email" runat="server"/>
    <asp:textbox id="Password" runat="server"/>
    <asp:Button id="Button1" OnClick="OnButtonClick" runat="server" Text="Login"/>
  </form>
  <asp:Label ID="labelResult" runat="server" />
</asp:Content>

Then on click in the code behind do something like this:

 protected  void OnButtonClick(object sender, EventArgs e)
        {
            HttpWebRequest req = WebRequest.Create("http://localhost:35810/Users/Login/") as HttpWebRequest;

            String userString = UsefulStuff.Serialization.SerializationUtil.
                SerializeDataContractToString(typeof(User), new User() { Email =  new Email(textboxUsername.text),
                                                                         Password = new Password(textboxPassword.text) });

            String strResponse = GetHttpPostResponse(req, userString);

            User recievedUser = UsefulStuff.Serialization.SerializationUtil.DeserializeDataContractString(
                typeof(User), strResponse) as User;

            labelResult.Text = recievedUser.SessionId;
        }


        public static String GetHttpPostResponse(HttpWebRequest httpWebRequest, String serializedPayload)
        {
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "text/xml";
            httpWebRequest.ContentLength = serializedPayload.Length;

            StreamWriter streamOut = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.ASCII);
            streamOut.Write(serializedPayload);
            streamOut.Close();

            StreamReader streamIn = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());

            string strResponse = streamIn.ReadToEnd();
            streamIn.Close();

            return strResponse;
        }

解决方案

Basic approach to call REST service is by HttpWebRequest

// User object serialized to XML
XElement data = new XElement("User",
  new XElement("UserName", UserName),
  new XElement("Password", Password)
);

MemoryStream dataSream = new MemoryStream();
data.Save(dataStream);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(YourServiceUrl);
request.Method = "POST";
request.ContentType = "application/xml";
// You need to know length and it has to be set before you access request stream
request.ContentLength = dataStream.Length; 

using (Stream requestStream = request.GetRequestStream())
{
  dataStream.CopyTo(requestStream);   
  requestStream.Close();
} 

HttpWebResponse response = request.GetResponse();
if (response.Status == HttpStatusCode.Unauthorized)
{
  ...
}
else
{
  ...
}
response.Close();

这篇关于消费WCF休息4从ASP。净的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆