Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        2年前关闭。
                                                                                            
                
        
我是创建Web Api的新手,我需要将字符串传递给GetAsync方法,但是我不知道我应该向WebApiConfig文件中添加什么以及更改后如何在GetAsync上添加。我在这里搜索过,但没有发现任何对我有帮助的东西。谁能帮我吗?

我的程序:

private async void registrarServico(string nomeServico)
{
    using (HttpClient clientGet = new HttpClient())
    using (HttpClient clientSet = new HttpClient())
    {
        clientGet.BaseAddress = new Uri("api/ControladorServico/GetServico");
        var respostaGet = await clientGet.GetAsync("", nomeServico); //ERROR HERE!
    }
}


我的WebApiConfig:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);


我的API方法:

[HttpGet]
public IHttpActionResult GetServico(string nomeServico)
{
    try
    {
        return Ok(controladorServicoRep.CONTROLADOR_SERVICOSep.Get(d => d.NOME == nomeServico && d.MAQUINA == nomeMaquina).FirstOrDefault());
    }
    catch (Exception)
    {
        throw;
    }
}


谢谢。

最佳答案

好做这样的事情:

public async Task<TResult> GetAsync<TResult>(string uriString) where TResult : class
    {
        var uri = new Uri(uriString);
        using (var client = GetHttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(uri);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                //Log.Error(response.ReasonPhrase);
                return default(TResult);
            }
            var json = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<TResult>(json, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
        }
    }


然后,您可以将其称为:

var uriString = string.Format("{0}/{1}", "http://hostaddress/api/ControladorServico/GetServico", nomeServico);
var result = await GetAsync<YourModel>(uriString);

10-05 22:34