【问题标题】:UWP (Universal Windows Platform) Web Service in Visual Studio 2015 C#Visual Studio 2015 C# 中的 UWP(通用 Windows 平台)Web 服务
【发布时间】:2016-12-17 20:39:40
【问题描述】:

我是 StackOverflow 和 UWP 的新手。我用 C# 编程差不多 2 年了,但以前从未用过 UWP。

由于 UWP 不承认数据库直接连接,我试图创建一个 Web 服务。现在,我在 Visual Studio 的 Web 服务文件中默认使用“Hello World”并尝试在 UWP 应用程序中进行引用,但我无法制作一个简单的文本块来显示该方法在 Web 服务中的作用(返回一个“你好世界”)。所以这里是代码:

1) 默认为 Web 服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebService
{
    [WebService(Namespace = "http://tempuri.org/",Name ="Transfer")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}
}

2) UWP 应用程序

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;


namespace UWPWSApp
{

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            WebServiceTransfer.TransferSoapClient tsc = new WebServiceTransfer.TransferSoapClient();
        }
    }
}

所以问题来了,因为我看到一个“HelloWorldAsync()”,这里是一个屏幕:

ScreenCapture

我已经尝试过使用异步方法,但似乎不是显示“Hello World”的方法。

【问题讨论】:

    标签: c# sql web-services visual-studio-2015 win-universal-app


    【解决方案1】:

    首先tsc.HelloWorldAsync()方法是一个异步方法:

    当你使用这个方法时,你需要使用 await 操作符,并且你必须在你使用这个 await 操作符的方法声明中包含“async”关键字。

    public MainPage()
    {
        this.InitializeComponent();
    }
    

    这是 MainPage 的构造函数,它初始化 MainPage 类的一个新实例。它不是方法,构造函数不能与 await 运算符一起使用,因此您可以在此处使用 Loaded event

    其次,我看到你的代码是这样的:

    textBlock.Text = tsc.HelloWorldAsync();
    

    TextBlockText 属性应该是一个字符串,但是tsc.HelloWorldAsync() 返回一个HelloWorldResponse 类型,正如你在我的图片中看到的那样,这里的类型不匹配,所以你可以这样编码这个:

    public MainPage()
    {
        this.InitializeComponent();
        this.Loaded += MainPage_Loaded;
    }
    
    private async void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        WebServiceTransfer.TransferSoapClient tsc = new WebServiceTransfer.TransferSoapClient();
        var response = await tsc.HelloWorldAsync();
        textBlock.Text = response.Body.HelloWorldResult;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 2016-08-24
      • 1970-01-01
      • 2016-08-25
      相关资源
      最近更新 更多