Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

c# - How to pass content body to API Get method

Once I'm trying to call web API controller method I'm getting this error,

Cannot send a content-body with this verb-type.

My Details controller as follows,

[HttpGet("requestDetails/Details")]
public IActionResult GetDetails([FromHeader] int tenantId,[FromBody]ParamterDTO pdto)
{
    try
    {
        var details = Service.GetDetials(pdto.FromDate, pdto.SearchText, pdto.UserId);
        return Ok(details);
    }
    catch (Exception)
    {
        return StatusCode(500);
    }
}

This how I consume Details controller method.

public string GetDetails(string fromDate, string searchText, string userID) {

  try {
    string serviceUrl = "http://localhost/Testapi/api/details/requestDetails/Details";

    string jsonParamterData = new JavaScriptSerializer().Serialize(new {
      FromDate = fromDate,
        SearchText = searchText,
        UserId = userID
    });

    HttpClient client = new HttpClient();

    HttpMethod method = new HttpMethod("GET");
    HttpRequestMessage message = new HttpRequestMessage(method, serviceUrl);

    StringContent content = new StringContent(jsonParamterData, Encoding.UTF8, "application/json");
    client.DefaultRequestHeaders.Add("TenantId", tenantId.ToString());
    client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token));
    message.Content = content;

    var response = client.SendAsync(message).Result;
    client.Dispose();
    return response.Content.ToString();
  } catch (Exception ex) {
    NameValueCollection logParams = new NameValueCollection();
    Logger.LogErrorEvent(ex, logParams);
    throw;
  }
}

Can anyone explain me, what did I do wrong here.

Updated:

I used post instead of get by changing code as,

HttpMethod method = new HttpMethod("POST");
HttpRequestMessage message = new HttpRequestMessage(method, serviceUrl);

StringContent content = new StringContent(jsonParamterData, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("TenantId", tenantId.ToString());
client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token));
message.Content = content;
//var response = client.GetStringAsync(message.).Result;
var response = client.SendAsync(message);

but response result showing as follows,

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to change your action to this:

[Route("requestDetails/Details")]
public ActionResult<Details> GetDetails([FromBody] ParamterDTO pdto)
{
    try
    {
return Service.GetDetials(pdto.FromDate, pdto.SearchText, pdto.UserId);
    //or you can try    
return Ok(Service.GetDetials(pdto.FromDate, pdto.SearchText, pdto.UserId)); 
   // but you need special deserialization
      
    }
    catch (Exception)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, new Details());
    }
}

And change your request code to this:

using (var client = new HttpClient())
{
    ....your code 
        
    
    var response = client.SendAsync(message);

    if (response.IsSuccessStatusCode)
    {
        return response.Content.ReadAsStringAsync().Result;
                
    }
   ````your code
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...