简体   繁体   English

通过Web客户端返回400错误请求

[英]posting with web client returning a 400 bad request

EDIT. 编辑。 The people who suggested fiddler were great. 建议提琴手的人很棒。 Turns out the API i was posting to freaked out because the c# application had no user-agent. 原来我发布的API很奇怪,因为C#应用程序没有用户代理。 So adding one to the header fixed it 所以在标题中添加一个固定

I'm trying to use c# web client to to post to an api but seem to be running into a wall. 我正在尝试使用C#Web客户端发布到api,但似乎遇到了麻烦。 I'm trying to use this code to post json to an api however all i get is 400 bad request and i'm not sure what is going on. 我正在尝试使用此代码将json发布到api,但是我得到的只是400个错误的请求,我不确定发生了什么。

output = "{ \"id\": \"xxxxxx\", \"company\": \"test\", \"fname\": \"test\", \"lname\": \"test\", \"member_level\": \"Member\",\"status\": \"active\"}";

using (var client = new WebClient())
{
     client.Headers.Add("token", "validtoken");
     client.Headers.Add("Content-Type", "application/json");
     client.UploadString(new Uri("url"), "POST", output);
}

I was able to use powershell to successfully post using a webrequest so i know the url and auth token are valid. 我能够使用powershell成功使用webrequest发布信息,因此我知道url和auth令牌有效。 but for whatever reason i can't get c# to post correctly. 但是无论出于什么原因,我都无法使C#正确发布。 This is the working powershell command 这是有效的powershell命令

curl url -Method POST -H @{"token" = "token"} -ContentType "application/json" -Body '{ "id": "xxxxxx", "company": "test", "fname": "test", "lname": "test", "member_level": "test","status": "active"}'

instead of 代替

client.UploadString(new Uri("url"), "POST", output);

use 采用

client.UploadData(url, "POST", Encoding.UTF8.GetBytes(output));

Just use built-in features of C# to keep code clean. 只需使用C#的内置功能即可保持代码干净。 When possible create classes that describe contracts for API communication. 在可能的情况下,创建描述用于API通信的合同的类。 Use HttpClient when there is no need for low-level control. 不需要低级控制时,请使用HttpClient。 HttpClient can send these objects as JSON and you usually do not need to care about serialization issues. HttpClient可以将这些对象作为JSON发送,并且您通常不需要关心序列化问题。

This code should make a POST after you replaced url parts. 替换网址部分后,此代码应进行POST。 Since you do not send the TOKEN this should raise a 401 error - you are not authorized. 由于您没有发送令牌,因此应该会出现401错误-您无权。 Add your valid token, delete the comment and this request should work. 添加您的有效令牌,删除注释,此请求应该可以使用。

using System;
using System.Collections.Generic;
using System.Net.Http;

public class User
{
    public string Id { get; set; }
    public string Company { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public string MemberLevel { get; set; }
    public string Status { get; set; }
}

class Program
{
    static void CreateUser(User user)
    {
        using (var client = new HttpClient())
        {
            // posts to https://yourawesomewebsite.com/api/users
            client.BaseAddress = new Uri("https://yourawesomewebsite.com");             
            //client.Headers.Add("token", "validtoken");
            HttpResponseMessage response = client.PostAsJson("api/users", user);
            response.EnsureSuccessStatusCode();
        }
    }

    static void Main()
    {     
        // Create a new user
        User user = new User
        { 
            Id = "xxxxx",
            Company = "Test",
            FName = "Test",
            LName = "Test",
            MemberLevel = "Test",
            Status = "Active"
        };

        CreateUser(user);
    }
}

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM