如何从URL隐藏动作和控制器:ASP.NET MVC [英] How to hide action and controller from url : asp.net mvc

查看:183
本文介绍了如何从URL隐藏动作和控制器:ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介

我正在开发一个可以注册用户的演示应用程序.users表具有"username"字段."home"控制器中有"detail"操作,接受字符串"username"的参数.

I am working on demo application where users can register.Users table have "username" field.There is "detail" action in "home" controller accepting parameter of string "username".

代码

public ActionResult Detail (string username)
{
 return View();
}

然后该网址将是

www.example.com/home/Detail?username=someparam

www.example.com/home/Detail?username=someparam

问题

我可以设置这样的路线吗?

Can i setup route like that ?

www.example.com/someparam

www.example.com/someparam

如果可能的话,请告诉我.任何形式的帮助或参考将不胜感激.

If its possible, then please let me know. Any kind of help or reference will be appreciated.

感谢您的时间.

推荐答案

如果更改路由的定义方式,这是可行的.假设您使用的是点网4.5.2

That is doable if you change the way your routes are defined. Let's assume that you use dot net 4.5.2

在App_Start下查看RouteConfig.

Have a look in RouteConfig under App_Start.

典型的路由定义是这样定义的:

A typical route definition is defined like this :

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

将路线更改为以下内容无妨:

Nothing stops from changing the route to look like this :

routes.MapRoute(
name: "Default",
url: "{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

我们基本上是将控制器和操作硬编码为某个值,所以现在您只需输入url/paraname即可,它将达到硬编码组合.

We are basically hardcoding the controller and action to be a certain value so now you could just have url/paramname and it will hit the hardcoded combination.

话虽如此,我不会做这样的事情,因为它违反了MVC的工作方式

This being said I would not do things like this as it's against the way MVC works

MVC路由是url/controller/action.您可以跳过诸如索引之类的通用内容的操作,并且您的URL变为url/controller. MVC必须能够确定您要击中哪个控制器以及哪个动作,并且最好保持其惯例不变.

MVC routes are url/controller/action. You can skip the action for generic stuff like an Index for example and your URL becomes url/controller. MVC needs to be able to identify which controller you want to hit and which action and it's best to stay within the conventions it has.

此外,每个应用程序通常都具有多个控制器,这可以很好地分离问题.现在,您已经对自己进行了硬编码,使其只有一个控制器和一个动作.

Plus, each application will typically have more than one controller, which allows a nice Separation of Concerns. Now you've hardcoded yourself ito having just one controller and action.

尽管您所建议的内容可以通过Webforms的方式轻松完成,但也许您希望对此进行调查.

What you are suggesting can be done a lot easier in a webforms manner though so maybe you want to look into that.

这篇关于如何从URL隐藏动作和控制器:ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆