簡體   English   中英

使用參數調用方法

[英]Call the method using the parameter

我如何使用URL中的參數調用控制器的方法。

例如:(無法修改URL)

url #1: example.com/somecontroller?method=function1&param1="login"

url #2: example.com/somecontroller?method=function2&param1="login"&param2="pass"

在控制器中,我們有兩種方法:

public class SomeController:BaseController{

   public void function1(string param1)
    {
    //logic
    }

    public void function2(string param1, string param2)
    {
    //logic
    }
}

有什么想法嗎?

生成路線后,您的鏈接應如下所示:

http://example.com/somecontroller/function1?param1="login"

其中login是function1方法的param1。

這是路線可能的示例:

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

您不能在路由中指定查詢字符串,但是可以僅為控制器創建路由,並具有一個通用的actionresult,它根據您的querystring值選擇要返回的actionresult:

routes.MapRoute(
    name: "Distributor",
    url: "{controller}",
    defaults: new { action = "Distributor" }
);

和您的新控制器動作:

    public ActionResult Distributor(string method)
    {

        switch (method)
        {
            case "MyMethod1":
                return MyMethod1();
            case "MyMethod2":
                return MyMethod2();
            default:
                return new HttpNotFoundResult();


        }
    }

這使您可以保留/ {controller}?method = {methodName}&param1 = login的網址格式

您必須以不同的方式處理每種方法的預期參數-例如,您可以這樣做:

    public ActionResult Distributor(string method)
    {

        switch (method)
        {
            case "MyMethod1":
                return MyMethod1(Request.QueryString["param1"]);
            case "MyMethod2":
                return MyMethod2(Request.QueryString["param1"], Request.QueryString["param2"]);
            default:
                return new HttpNotFoundResult();


        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM