Custom header to HttpClient request

前端 未结 4 1739
走了就别回头了
走了就别回头了 2020-11-27 03:38

How do I add a custom header to a HttpClient request? I am using PostAsJsonAsync method to post the JSON. The custom header that I would need to b

4条回答
  •  生来不讨喜
    2020-11-27 04:18

    var request = new HttpRequestMessage {
        RequestUri = new Uri("[your request url string]"),
        Method = HttpMethod.Post,
        Headers = {
            { "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
            { HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
            { HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
        },
        Content = new MultipartContent { // Just example of request sending multipart request
            new ObjectContent<[YOUR JSON OBJECT TYPE]>(
                new [YOUR JSON OBJECT TYPE INSTANCE](...){...}, 
                new JsonMediaTypeFormatter(), 
                "application/json"), // this will add 'Content-Type' header for the first part of request
            new ByteArrayContent([BINARY DATA]) {
                Headers = { // this will add headers for the second part of request
                    { "Content-Type", "application/Executable" },
                    { "Content-Disposition", "form-data; filename=\"test.pdf\"" },
                },
            },
        },
    };
    

提交回复
热议问题