c# - Response.Redirect 给出 HttpException 异常

标签 c# asp.net web httpresponse

我正在创建 Web 应用程序,我在重定向到另一个页面时遇到问题,如果我在另一种方法中使用重定向代码,那么它工作正常,但我想使用我正在运行的线程中的重定向代码,它向我抛出 HttpExeption。请看一下这段代码并展示在我的 runloop() 方法中使用重定向代码的正确方法。提前致谢。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using System.Threading.Tasks;

public partial class _Default : System.Web.UI.Page
{
static TcpListener listener;
static TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public String receive = "kkkk";
public String text_to_send;
string Jsn;
string URI ;
string myParameters;
string URL1;

Thread backgroundThread2;
Thread backgroundThread;
int i, n = 0, k = 0, len = 0, len2 = 0;
public int readflag = 0, writeflag = 0, pre1 = 0, pre2 = 0, pre3 = 0, nopre = 0;
char[] ch = new char[100];
char[] ch1 = new char[100];
char[] ch2 = new char[100];
String test = null, s1, s2, s3;
String test1 = null;
string frame;
const int LIMIT = 5; //5 concurrent clients
protected void Page_Load(object sender, EventArgs e)
{
     frame = Request.QueryString["frame"];
    if (Request.QueryString["Frame"] != null)
        Response.Write("From Page1 param1 value=" + Request.QueryString["frame"]);

}
public void Button1_Click(object sender, EventArgs e) //start server
{
    listener = new TcpListener(IPAddress.Any, 8002);
    listener.Start();

    client = listener.AcceptTcpClient();
    STR = new StreamReader(client.GetStream());
    STW = new StreamWriter(client.GetStream());
    STW.AutoFlush = true;


    backgroundThread = new Thread(new ThreadStart(RunLoop));
    backgroundThread.Start();
  //  Task.Delay(50000);
    //redirect1();

  //  Response.Redirect(URL1);

}

public void Button2_Click(object sender, EventArgs e) //Redirect server
{
    Jsn = "25";
    string URI = "Otherpage.aspx?";
    string myParameters = "jasonop="+ Jsn;
    string URL1 = URI + myParameters;

        Response.Redirect(URL1);

  //  Response.Redirect("Otherpage.aspx?jasonop=25");
 //   System.Diagnostics.Process.Start("http://localhost:85/shaktijason/1.php?jasonop=25");
}
public class Person
{
    public string Name { get; set; }
}
public void RunLoop()       //receive
{
    NetworkStream stream = client.GetStream();
    Byte[] bytes = new Byte[256];
    String data = null;
    int i,k=1;
    string str = "";
    JavaScriptSerializer js = new JavaScriptSerializer();
    // Loop to receive all the data sent by the client.
    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
    {
        // Translate data bytes to a ASCII string.
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
        byte[] bHex = Encoding.ASCII.GetBytes(data);
        // TextBox1.Text = data;
        string json = "[{Name:'01030008000105C8'}]";


        Person[] persons = js.Deserialize<Person[]>(json);
        string name = persons[0].Name.ToString();
        // STW.WriteLine("01030008000105C8")
        STW.WriteLine(name);
        string result = decodedata(data);
        str = result;
        k++;
        if (k == 4) { break; }

    }
    //   string returnJson = "[{Freq:'" + str + "'}]";
    Jsn = GetDeviceJSON(str);
     URI = "Otherpage.aspx?";
     myParameters = "jasonop="+Jsn;
     URL1 = URI + myParameters;

    Response.Redirect(URL1,false); 
  //  Response.Redirect("Otherpage.aspx");
    //string URI = "http://localhost:85/Shaktijason/1.php";
    //string myParameters = "jasonop=jsn";
    //using (WebClient wc = new WebClient())
    //{
    //    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    //    string HtmlResult = wc.UploadString(URI, myParameters);
    //    Response.Redirect(HtmlResult);
    //}
    //string JSON = Json;


    //backgroundThread2.Start();
    //  backgroundThread.Abort();
    //return js.Serialize(returnJson);

}
public string decodedata(string data)
{
    ch1 = data.ToCharArray();
    ch2 = data.ToCharArray();
    int len1 = data.Count(char.IsLetter);
    len2 = data.Count(char.IsNumber);
    int add = len1 + len2;
    while (ch1[k] != 'k')
    {
        ch2[k] = ch1[k];
        k++;
    }
    string strng = new string(ch2, 0, k);
    len = strng.Length;

    string sub = data.Substring(k + 1);
    len2 = sub.Length;
    k = 0;
    if (len == 1)
    {
        strng = "0" + strng.PadLeft(len, '0');
    }
    if (len2 == 1)
    {
        sub = "0" + sub.PadLeft(len2, '0');
    }
    char[] go = new char[20];
    string final = strng + sub;
    if (final.Equals("00b8"))
    {
        final = "0";
    }
    Decimal intAgain = long.Parse(final, System.Globalization.NumberStyles.HexNumber);


    intAgain = intAgain / 100;
    string final3 = intAgain.ToString();

    //  string final2 = new string(go);

    return final3;
}
[WebMethod]
public static string GetValues(string values)
{
    return values;
}
public string GetDeviceJSON(String str)
{
    Device[] emps = new Device[] {
    new Device()
    {
        Freq=str
    }
    //new employee()
    //{
    //    id=102,
    //    name="dinesh",
    //    salary=100000
    //}
    };
    return new JavaScriptSerializer().Serialize(emps);
  }

最佳答案

您正在尝试从后台线程访问 Reponse 对象,而响应早已消失。

在页面停止呈现后,您不能访问 Response 对象或 HttpContext 下的任何其他对象。使用网络套接字或 AJAX 调用创建异步请求和响应。

关于c# - Response.Redirect 给出 HttpException 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029465/

相关文章:

c# - 控制 web Essential 如何从 .cs 文件生成 d.ts 文件

c# - Entity Framework 5 方法查询汇总

c# - 在 ASP.NET 中处理数据时如何更新进度消息?

使用非侵入式验证时 jQuery 验证未执行

c# - 从在线资源统一将图像保存在移动设备上

c# - 将 XML 值反序列化为对象

c# - Razor 和 ASP.NET : the right way to test whether a record exists and use its fields?

c# - 如何使用 Entity Framework Core 在具有默认值的 boolean 值上设置另一个值?

css - 如何使侧边栏菜单固定,但 float 在右侧

html - style.css 不适用于我网站的虚拟主机预览,但它适用于本地 "offline"HTML 文件