【问题标题】:webClient POST does not workwebClient POST 不起作用
【发布时间】:2016-06-05 16:02:49
【问题描述】:

我正在尝试使用 webClient 将表单发布到服务器。这是我的请求代码。

WebClient myWebClient = new WebClient();

NameValueCollection myNameValueCollection = new NameValueCollection();

myNameValueCollection.Add("about", about);
myNameValueCollection.Add("firstname", firstname);
myNameValueCollection.Add("lastname", lastname);
Uri uri = new Uri("http://192.168.1.102:1992/api/member/updateprofile");
myWebClient.UploadValuesAsync(uri,"POST", myNameValueCollection);

此请求无法到达服务器。我已经检查了 Url,它是正确的,因为我可以使用 fiddler 并使用 httpWebRequest 客户端发出请求。我看不出我的代码有什么问题。这可能是什么问题?

我的服务器端代码如下:

[HttpPost]
[Route("updateprofile")]
public HttpResponseMessage updateProfile()
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);

    var httpRequest = HttpContext.Current.Request;

    return result;
}

【问题讨论】:

  • 好的,您正在显示动作的属性路由。但没有与您显示的 url 匹配的控制器路由/路由前缀的详细信息。确认路由并正确配置它们。

标签: c# asp.net-web-api webclient


【解决方案1】:

好的,您正在显示动作的属性路由。但没有与您显示的 url 匹配的控制器路由/路由前缀的详细信息。

[RoutePrefix("api/member")]
public class MemberController : ApiController {

    //eg POST api/member/updateprofile
    [HttpPost]
    [Route("updateprofile")]
    public HttpResponseMessage updateProfile() {
        var result = new HttpResponseMessage(HttpStatusCode.OK);

        var httpRequest = HttpContext.Current.Request;

        return result;
    }
}

确认您的路线以及您正在正确配置它们。

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

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

【讨论】:

  • 路由配置正确。 RoutePrefix 看起来像这样:[RoutePrefix("api/member")]。网址没有问题。我已经用 Fiddlerand 进行了检查,它工作正常。
  • 保持 fiddler 运行,并在执行代码时查看它所看到的内容。检查原始请求并将其与有效的请求进行比较。这应该让您了解可能导致您的问题的原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2016-06-10
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多