Asp.Net MVC : 내 URL에서 대시를 어떻게 활성화합니까?
URL에 대시로 구분 된 단어를 추가하고 싶습니다. 그래서 대신 :
/MyController/MyAction
내가 좋아하는 것:
/My-Controller/My-Action
이것이 가능한가?
다음과 같이 ActionName 속성을 사용할 수 있습니다.
[ActionName("My-Action")]
public ActionResult MyAction() {
return View();
}
그런 다음보기 파일을 "My-Action.cshtml"(또는 적절한 확장자)로 불러야합니다. 또한 Html.ActionLink 메소드에서 "my-action"을 참조해야합니다.
컨트롤러에 대한 간단한 솔루션은 없습니다.
편집 : MVC5 업데이트
전역 적으로 경로를 활성화합니다.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
// routes.MapRoute...
}
이제 MVC5에서는 속성 라우팅이 프로젝트에 흡수되었습니다. 이제 다음을 사용할 수 있습니다.
[Route("My-Action")]
행동 방법.
컨트롤러의 경우 RoutePrefix해당 컨트롤러의 모든 작업 메서드에 적용될 속성을 적용 할 수 있습니다 .
[RoutePrefix("my-controller")]
사용의 이점 중 하나 RoutePrefix는 URL 매개 변수가 모든 조치 메소드로 전달된다는 것입니다.
[RoutePrefix("clients/{clientId:int}")]
public class ClientsController : Controller .....
한조각..
[Route("edit-client")]
public ActionResult Edit(int clientId) // will match /clients/123/edit-client
이 블로그에 표시된대로 사용자 지정 경로 처리기를 만들 수 있습니다.
http://blog.didsburydesign.com/2010/02/how-to-allow-hyphens-in-urls-using-asp-net-mvc-2/
public class HyphenatedRouteHandler : MvcRouteHandler{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
return base.GetHttpHandler(requestContext);
}
}
... 그리고 새로운 경로 :
routes.Add(
new Route("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller = "Default", action = "Index", id = "" }),
new HyphenatedRouteHandler())
);
매우 유사한 질문이 여기에 제기되었습니다. 하이픈이있는 URL에 대한 ASP.net MVC 지원
이 문제를 위해 EveryMvc / Url을 every-mvc / url로 암시 적으로 변환 하는 오픈 소스 NuGet 라이브러리 를 개발했습니다 .
대문자 URL은 쿠키 경로가 대소 문자를 구분하기 때문에 문제가 있습니다. 대부분의 인터넷은 실제로 대소 문자를 구분하지만 Microsoft 기술은 URL을 대소 문자를 구분하지 않습니다. ( 내 블로그 게시물에 대한 추가 정보 )
NuGet 패키지 : https://www.nuget.org/packages/LowercaseDashedRoute/
설치하려면 프로젝트를 마우스 오른쪽 단추로 클릭하고 NuGet 패키지 관리자를 선택하여 Visual Studio에서 NuGet 창을 열고 "온라인"탭에서 "Lowercase Dashed Route"를 입력하면 팝업됩니다.
또는 패키지 관리자 콘솔 에서이 코드 를 실행할 수 있습니다 .
Install-Package LowercaseDashedRoute
그런 다음 App_Start / RouteConfig.cs를 열고 기존 route.MapRoute (...) 호출을 주석 처리하고 대신 다음을 추가해야합니다.
routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
new DashedRouteHandler()
)
);
그게 다야. 모든 URL은 소문자, 파선이며 더 이상 수행하지 않고 암시 적으로 변환됩니다.
오픈 소스 프로젝트 URL : https://github.com/AtaS/lowercase-dashed-route
다음은 ASP.NET MVC 5에서 영역을 사용하여 수행 한 작업이며 매력적으로 작동했습니다. 내 뷰의 이름도 바꿀 필요가 없었습니다.
RouteConfig.cs에서 다음을 수행하십시오.
public static void RegisterRoutes(RouteCollection routes)
{
// add these to enable attribute routing and lowercase urls, if desired
routes.MapMvcAttributeRoutes();
routes.LowercaseUrls = true;
// routes.MapRoute...
}
컨트롤러에서 클래스 정의 앞에 다음을 추가하십시오.
[RouteArea("SampleArea", AreaPrefix = "sample-area")]
[Route("{action}")]
public class SampleAreaController: Controller
{
// ...
[Route("my-action")]
public ViewResult MyAction()
{
// do something useful
}
}
The URL that shows up in the browser if testing on local machine is: localhost/sample-area/my-action. You don't need to rename your view files or anything. I was quite happy with the end result.
After routing attributes are enabled you can delete any area registration files you have such as SampleAreaRegistration.cs.
This article helped me come to this conclusion. I hope it is useful to you.
Asp.Net MVC 5 will support attribute routing, allowing more explicit control over route names. Sample usage will look like:
[RoutePrefix("dogs-and-cats")]
public class DogsAndCatsController : Controller
{
[HttpGet("living-together")]
public ViewResult LivingTogether() { ... }
[HttpPost("mass-hysteria")]
public ViewResult MassHysteria() { }
}
To get this behavior for projects using Asp.Net MVC prior to v5, similar functionality can be found with the AttributeRouting project (also available as a nuget). In fact, Microsoft reached out to the author of AttributeRouting to help them with their implementation for MVC 5.
You could write a custom route that derives from the Route class GetRouteData to strip dashes, but when you call the APIs to generate a URL, you'll have to remember to include the dashes for action name and controller name.
That shouldn't be too hard.
You can define a specific route such as:
routes.MapRoute(
"TandC", // Route controllerName
"CommonPath/{controller}/Terms-and-Conditions", // URL with parameters
new {
controller = "Home",
action = "Terms_and_Conditions"
} // Parameter defaults
);
But this route has to be registered BEFORE your default route.
If you have access to the IIS URL Rewrite module ( http://blogs.iis.net/ruslany/archive/2009/04/08/10-url-rewriting-tips-and-tricks.aspx ), you can simply rewrite the URLs.
Requests to /my-controller/my-action can be rewritten to /mycontroller/myaction and then there is no need to write custom handlers or anything else. Visitors get pretty urls and you get ones MVC can understand.
Here's an example for one controller and action, but you could modify this to be a more generic solution:
<rewrite>
<rules>
<rule name="Dashes, damnit">
<match url="^my-controller(.*)" />
<action type="Rewrite" url="MyController/Index{R:1}" />
</rule>
</rules>
</rewrite>
The possible downside to this is you'll have to switch your project to use IIS Express or IIS for rewrites to work during development.
I'm still pretty new to MVC, so take it with a grain of salt. It's not an elegant, catch-all solution but did the trick for me in MVC4:
routes.MapRoute(
name: "ControllerName",
url: "Controller-Name/{action}/{id}",
defaults: new { controller = "ControllerName", action = "Index", id = UrlParameter.Optional }
);
참고URL : https://stackoverflow.com/questions/30310/asp-net-mvc-how-do-i-enable-dashes-in-my-urls
'Program Club' 카테고리의 다른 글
| 배열의 Ruby 출력 내용을 쉼표로 구분 된 문자열 Ruby (0) | 2020.10.20 |
|---|---|
| Rails-정의되지 않은 메소드`stringify_keys ' (0) | 2020.10.20 |
| gcc -ggdb와 gcc -g의 차이점은 무엇입니까? (0) | 2020.10.19 |
| 가상 소멸자는 상속됩니까? (0) | 2020.10.19 |
| C ++ 템플릿 클래스를 전달하는 방법은 무엇입니까? (0) | 2020.10.19 |