简体   繁体   English

从ASP消耗WCF Rest 4。 净

[英]Consuming WCF Rest 4 From ASP . NET

I am a complete ASP .NET newbie. 我是一个完整的ASP .NET新手。 I've written a set of web services using the WCF 4 Rest Starter Kit. 我已经使用WCF 4 Rest Starter Kit编写了一组Web服务。 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. 我从Flash应用程序中调用所有内容,但是我想编写一个快速且肮脏的管理面板供自己使用,而无需用Flash编写。

I figure it will be faster to get this up and running in ASP. 我认为在ASP中启动并运行它会更快。 So the question is consider a WCF function like this: 因此,问题是考虑这样的WCF函数:

[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). 我将如何从带有用户名,密码,提交框的ASP .Net页面使用它,或者显示错误401的错误或成功(returneduser.sessionid)。

Thanks! 谢谢!

Note: I am aware of how to call a Rest service over Http in C#. 注意:我知道如何在C#中通过Http调用Rest服务。 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中是否应该有一种“不错的方法”,或者只是做成像这样的形式:

<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 调用REST服务的基本方法是通过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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM