gpt4 book ai didi

c# - 在另一个 Controller 中将责任从短 URL 重定向到完整 URL

转载 作者:行者123 更新时间:2023-11-30 17:30:39 24 4
gpt4 key购买 nike

作为家庭作业,我必须做一个简单的 URL 缩短器,我可以在其中添加完整链接到列表,由 Hashids.net library 处理,然后我得到一个 URL 的简短版本。

CLICK

我现在有这样的东西,但我无法将它重定向回完整链接。

我想添加一个新 Controller ,它将负责将短 URL 重定向到完整 URL。单击短 URL 后,它应该转到 localhost:xxxx/ShortenedUrl,然后重定向到完整链接。任何提示我如何创建这个?

我试图通过 @Html.ActionLink(@item.ShortenedLink, "Index", "Redirect")return Redirect(fullLink) 在重定向中做到这一点 Controller ,但它没有像我预期的那样工作。

还有一个关于路由的问题,点击短 URL 后如何实现它会给我 localhost:XXXX/ShortenedURL(即 localhost:XXXX/FSIAOFJO2@ ).现在我有

<a href="@item.ShortenedLink">@Html.DisplayFor(model => item.ShortenedLink)</a> 

app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Link}/{action=Index}");
});

但它给了我 localhost:XXXX/Link/ShortenedURL,所以我想在 URL 中省略这个链接。

查看(短网址部分):

 <td>@Html.ActionLink(item.ShortenedLink,"GoToFull","Redirect", new { target = "_blank" }))</td>

链接 Controller :

public class LinkController : Controller
{
private ILinksRepository _repository;

public LinkController(ILinksRepository linksRepository)
{
_repository = linksRepository;
}

[HttpGet]
public IActionResult Index()
{
var links = _repository.GetLinks();
return View(links);
}

[HttpPost]
public IActionResult Create(Link link)
{
_repository.AddLink(link);
return Redirect("Index");
}

[HttpGet]
public IActionResult Delete(Link link)
{
_repository.DeleteLink(link);
return Redirect("Index");
}
}

我正在尝试做的重定向 Controller :

private ILinksRepository _repository;

public RedirectController(ILinksRepository linksRepository)
{
_repository = linksRepository;
}

public IActionResult GoToFull()
{
var links = _repository.GetLinks();
return Redirect(links[0].FullLink);
}

有没有更好的方法来访问重定向 Controller 中的链接列表?

最佳答案

这是我的建议,通过 AJAX 触发链接,这里是工作示例:

这是通过模型绑定(bind)的 HTML 元素:

@Html.ActionLink(Model.ShortenedLink, "", "", null, 
new { onclick = "fncTrigger('" + "http://www.google.com" + "');" })

这是 javascript ajax 代码:

function fncTrigger(id) {

$.ajax({
url: '@Url.Action("TestDirect", "Home")',
type: "GET",
data: { id: id },
success: function (e) {
},
error: function (err) {
alert(err);
},
});
}

然后在您的 Controller 上接收 ajax 点击:

 public ActionResult TestDirect(string id)
{
return JavaScript("window.location = '" + id + "'");
}

基本上我在这里做的是,在我单击链接后,它将调用 TestDirect 操作,然后使用传递的 url 参数将其重定向。您可以在此操作中进行转换。

关于c# - 在另一个 Controller 中将责任从短 URL 重定向到完整 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49391997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com