Accessing the query string in ASP.Net Web Api?

后端 未结 3 1889
礼貌的吻别
礼貌的吻别 2020-12-14 06:09

I\'m using the default template generated by Asp.net Web Api. I\'m working with the Get() Part:

        // GET api/values
    public IEnumerable

        
相关标签:
3条回答
  • 2020-12-14 06:47

    Even though @Kiran Challa's answer is correct, there are few situations that you might prefer to get URL parameters directly from the URL. in those scenarios, try this:

    using System.Net.Http;
    
    var allUrlKeyValues = ControllerContext.Request.GetQueryNameValuePairs();
    
    string p1Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p1").Value;
    string p2Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p2").Value;
    string p3Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p3").Value;
    

    Now for the following URL, p1Val will be "Apple", p2Val will be "Banana", and p3Val will be null.

    .../api/myController?p1=Apple&p2=Banana
    

    Update:

    Thanks for the suggestions, now, the source code for this test is in GitHub and it also runs and can be tested on Azure:

    • http://freewebapi.azurewebsites.net/api/values?p1=Apple&p2=Banana
    0 讨论(0)
  • 2020-12-14 06:56

    The query string key name should match the parameter name of the action:

    /api/values?queryString=f

    public IEnumerable<string> Get(string queryString)
        {
            return new string[] { "value3", "value4" };
        }
    
    0 讨论(0)
  • 2020-12-14 07:01

    There is one more way to get query string as shown below when you are using wildcard in route or for dynamic routes.

    string query = ControllerContext.HttpContext.Request.QueryString.Value;
    

    BONUS:)

    string path = ControllerContext.HttpContext.Request.Path.ToUriComponent();
    
    0 讨论(0)
提交回复
热议问题