MVC动态URL

时间:2014-10-31 07:09:00

标签: .net url model-view-controller asp.net-mvc-5

据我所知,MVC模型中的url基于控制器。但我正面临这个问题,我无法绕过它:

  • 如果我正在设计一个饮料网站,我必须为每个品牌使用不同的URL。例如:beverage.com/pepsi, beverage.com/cocacola, beverage.com/sprit, beverage.com/7up。这些网址都将导致同一页面名为productdescription,唯一的区别是描述(图片,成分,价格等)

  • 这项任务是否有任何有效的方法?我不想为每种产品创造新的控制器!

2 个答案:

答案 0 :(得分:1)

假设您的公共控制器名称为ProductController且方法名称为Description。 现在在RouteConfig.cs中,您可以添加如下所述的路线:

routes.MapRoute(
    "PepsiRoute",
    "Pepsi/{id}",
    new { controller = "Product", action = "Description", id = UrlParameter.Optional });

routes.MapRoute(
    "CockRoute",
    "Cock/{id}",
    new { controller = "Product", action = "Description", id = UrlParameter.Optional });

注意:以上路线应放在默认路线之前。否则,您将面临运行时异常The controller for path '{PATH}' could not be found.

<强>更新

对于多个品牌,如果您不想为特定品牌注册路线,那么您可以按照以下说明映射路线:

routes.MapRoute(
    "AllBrand",
    "Product/{name}/{id}",
    new { controller = "Home", action = "About", id = UrlParameter.Optional });

然后您的网址将是:

  • {域} /产品/百事可乐
  • {域} /产品/百事可乐/ 2
  • {域} /产品/公鸡/ 14
  • {域} /产品/公鸡

    等...

答案 1 :(得分:0)

您正在寻找一个Rest Controller。以下是步骤:

1 - 声明你的rest servlet和web.xml(Websphere示例):

<servlet>
    <servlet-name>MyRestServlet</servlet-name>
    <servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>mipackage.MyRestServlet</param-value>
    </init-param>
    <init-param>
        <param-name>requestProcessorAttribute</param-name>
        <param-value>2</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>MyRestServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

2 - 实现RestServlet

import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;

public class RestServlet extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(BeverageController.class);
        return classes;
    }

}    

3 - 实施您的Rest控制器:

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

@Path("/{beverage}")
@ApplicationScoped
public class BeverageController {
    {
        @GET
        public String getBeverage(@PathParam("beverage") String beverage){
            //fetch order
        }
    }  
}