简体   繁体   中英

How to route legacy QueryString parameters in ASP.Net MVC 3?

I am using a third party service that does an async callback to a URL I provide to them. So I tell them to use http://www.mysite.com/Status/Incoming . This must obviously map to an Incoming() method on my StatusController.

However, what I don't have control over is the format of the parameters they call my URL with. Eg They will do a callback such as: http://www.mysite.com/Status/Incoming?param1=val1&param2=val2&param3=val3

I want to map this to the parameters of my action method: Incoming(string param1, string param2, int param3)

How do I do this?

I have found a lot of stuff about custom routing, but nothing about legacy QueryString parameters.

There is no such thing as legacy query string parameters . There are query string parameters and they are part of the HTTP specification. And assuming that the http://www.mysite.com/Status/Incoming?param1=val1&param2=val2&param3=val3 url is called you don't need any route to make it map to the following action (the default route will do just fine):

public ActionResult Incoming(string param1, string param2, string param3)
{
    ...
}

The default model will take care of binding those values.

Why not use a catch all?

        routes.MapRoute(
            "Incoming", 
            "Status/Incoming/{*path}", // URL with parameters
            new { controller = "Status", action = "Incoming"} 
        );

then in your controller,

  public ActionResult Incoming(string path){
        //  the next line would probably be better off in a model binder, but this works:
        var dictionary = path
            .Substring(path.IndexOf("?")+1)
            .Split("&")
            .Select(x =>
                        {
                            var kvArray = x.Split("=");
                            return new KeyValuePair<string, string>(kvArray[0], kvArray[1]);
                        })
                        .ToDictionary(x=>x.Key,x=>x.Value);
           return Incoming(dictionary);
  }

  public ActionResult Incoming(Dictionary<string,string> dictionary){
       //do stuff
  }

All that being said, I think using the Request.QueryString is probably a better approach. As long as you are using MVC, it is accessible from your controller. However, if you can guarantee that the correct parameters will be passed then Darin's approach is going to be the best choice.

When I've had to deal with this before now, I just use the "legacy" call of Request.QueryString. It still works, even if it isn't very graceful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM