HttpClient PutAsync不向api发送参数

编程入门 行业动态 更新时间:2024-10-25 20:23:39
本文介绍了HttpClient PutAsync不向api发送参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在控制器上的放置如下:

On the controller Put is as following:

[HttpPut] [ActionName("putname")] public JsonResult putname(string name) { var response = ... return Json(response); }

问题在于通过以下方式使用此API时

The issue is on the when consuming this API via following

using (httpClient = new HttpClient()) { string name = "abc"; string jsonString = JsonConvert.SerializeObject(name); var requestUrl = new Uri("http:...../controller/putname/"); using (HttpContent httpContent = new StringContent(jsonString)) { httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result; }

此代码不会将参数名称传递给控制器​​.我什至尝试将uri更改为/putname/"+名称.

This code doesn't pass the parameter name to controller. I even tried changeing uri to /putname/" + name.

推荐答案

这对我有用:

var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}"; var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); var message = await _client.PutAsync(MakeUri("App/Rate"), httpContent); Assert.AreEqual(HttpStatusCode.NoContent, message.StatusCode);

和我的操作方法:

public void PutRate(AppRating model) { if (model == null) throw new HttpResponseException(HttpStatusCode.BadRequest); if (ModelState.IsValid) { // .. } }

和模型

public class AppRating { public int AppId { get; set; } public int PlatformId { get; set; } public decimal Rating { get; set; } }

-斯坦

更多推荐

HttpClient PutAsync不向api发送参数

本文发布于:2023-11-08 22:05:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不向   参数   HttpClient   PutAsync   api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!