本文介绍了将参数(字符串)传递给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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 21:48