例外:asp.net网站中的单线程公寓(STA)

时间:2013-11-17 13:08:58

标签: c# asp.net sta

我在asp.net网络表单中有这些方法:

public partial class currencies : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}

public class Rate
{
    public string to { get; set; }
    public string from { get; set; }
    public double rate { get; set; }
}

double ConvertedAmount { get; set; }

public void Convert(object sender, EventArgs e)
{
    DateTime theDate = DateTime.UtcNow;
    string todayDateTime = theDate.ToString("f");
    double amount = 0d;
    if (double.TryParse(txtAmount.Text.Trim(), out amount))
    {
        string url = string.Format("http://rate-exchange.appspot.com/currency?from={0}&to={1}", ddlFrom.SelectedItem.Value, ddlTo.SelectedItem.Value);
        WebClient client = new WebClient();
        string rates = client.DownloadString(url);
        Rate rate = new JavaScriptSerializer().Deserialize<Rate>(rates);
        ConvertedAmount = amount * rate.rate;
        Label1.Text = ddlFrom.SelectedItem.Value + ": " + amount;
        Label2.Text = ddlTo.SelectedItem.Value + ": " + ConvertedAmount;
        Label3.Text = "Rate as at " + todayDateTime + " is:";
        Label4.Text = " 1 " + ddlFrom.SelectedItem.Value + " = " + rate.rate + " " + ddlTo.SelectedItem.Value;

    }
    else
    {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Invalid amount value.');", true);
    }
}


protected void Button1_Click(object sender, EventArgs e)
{   
    Clipboard.SetText(ConvertedAmount.ToString());
}
}

当我单击按钮1将结果复制到剪贴板时,我得到异常:在调用OLE之前,必须将当前线程设置为单线程单元(STA)模式。这是我第一次处理这样的事情。 我应该怎么做才能解决这个问题?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

MSDN所述,

  

Clipboard类只能在设置为单线程的线程中使用   公寓(STA)模式。

不应要求在ASP.NET中设置STA。但是你确定要在服务器端的剪贴板上操作吗?您是否了解它将在服务器剪贴板上运行,而不是在客户端的剪贴板上运行?