将参数(字符串)传递给 GetAsync()? [英] Passing parameter (string) to GetAsync()?

查看:65
本文介绍了将参数(字符串)传递给 GetAsync()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是创建 Web Api 的新手,我需要将字符串传递给 GetAsync 方法,但我不知道应该向 WebApiConfig 文件添加什么以及更改后如何添加 GetAsync.我在这里搜索过,但没有找到对我有帮助的东西.有人可以帮我吗?

I'm new on creating Web Api's and I need to pass a string to GetAsync method but I don't know what should I add to WebApiConfig file and how on GetAsync after the change. I've searched here but I've found nothing that helped me. Can anyone help me please?

我的程序:

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:

My 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);

这篇关于将参数(字符串)传递给 GetAsync()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆