我试图制作一个简短的url mvc程序,一切都很好,但是重定向方法无效。
相信我:
我不知道为什么我得到空白页作为回报
public IActionResult Redirection(string url_return)
{
string final = null;
SqlConnection conn = new SqlConnection("Server=DESKTOP-28DDBR5\\SQLEXPRESS;Database=MakeItSmall;User Id=renan;Password=24025564;");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [BIG_URL] FROM [dbo].[URL_STORE] WHERE [SMALL_URL] = @URL_RETURN", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "@URL_RETURN";
param.Value = url_return;
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
final = (String.Format("{0}", reader[0]));
}
reader.Close();
conn.Close();
return Redirect(final);
}
}
路线:
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/{url_return}", (async context =>
{
string url_return = (string)context.Request.RouteValues["url_return"];
RedirectionController rc = new RedirectionController();
rc.Redirection(url_return);
}));
});
答案 0 :(得分:0)
请勿为此使用操作,只需将一个类添加到您的项目根目录,然后添加一个方法,该方法将在返回响应后返回所需的路径,如下所示
尝试此代码
public static class Utils
{
public static string Redirection(string url_return)
{
string final = null;
SqlConnection conn = new SqlConnection("Server=DESKTOP-28DDBR5\\SQLEXPRESS;Database=MakeItSmall;User Id=renan;Password=24025564;");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT [BIG_URL] FROM [dbo].[URL_STORE] WHERE [SMALL_URL] = @URL_RETURN", conn);
cmd.Parameters.AddWithValue("@URL_RETURN", url_return);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
final = (String.Format("{0}", reader[0]));
}
else
{
return "URL of page not found";
}
reader.Close();
conn.Close();
return final;
}
}
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapGet("/{url_return}", async context =>
{
await Task.Run(() =>
{
string url_return = (string)context.Request.RouteValues["url_return"];
string yourUrl = Utils.Redirection(url_return);
context.Response.Redirect(yourUrl);
//Tested//
//context.Response.Redirect("http://www.google.com");
}).ConfigureAwait(true);
});
});