标签: httpcontent

HttpContent边界双引号

我有这个代码示例作为另一个问题的答案发布(使用C#通过HTTP POST发送文件).除了一个问题,它工作正常.它用双引号括起HTTP头中的边界:

多部分/格式的数据; 边界= "04982073-787d-414B-a0d2-8e8a1137e145"

这窒息了我试图打电话的网络服务.浏览器没有那些双引号.我需要一些方法告诉.NET让他们离开.

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}
Run Code Online (Sandbox Code Playgroud)

c# boundary httpcontent

7
推荐指数
1
解决办法
1456
查看次数

设置HttpClient的授权标头

我有以下代码,我想将post请求的授权设置为:

Authorization:key=somevalue

using (HttpClient client = new HttpClient())
{
     using (StringContent jsonContent = new StringContent(json))
     {
         jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

         using (HttpResponseMessage response = await client.PostAsync("https://android.googleapis.com/gcm/send", jsonContent))
         {
            var reponseString = await response.Content.ReadAsStringAsync();
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

这该怎么做?我真的很挣扎以及以下声明

client.DefaultRequestHeaders.Add("Authorization", "key=" + apiKey);
Run Code Online (Sandbox Code Playgroud)

抛出以下异常

System.Net.Http.dll中出现"System.FormatException"类型的异常,但未在用户代码中处理

c# authorization httpclient httpcontent

6
推荐指数
1
解决办法
2万
查看次数

使用 Microsoft.Net.Http 将文件发送到服务

我有一个方法:

    private bool UploadFile(Stream fileStream, string fileName)
    {
            HttpContent fileStreamContent = new StreamContent(fileStream);
            using (var client = new HttpClient())
            {
                using (var formData = new MultipartFormDataContent())
                {
                    formData.Add(fileStreamContent, fileName, fileName);

                    var response = client.PostAsync("url", formData).Result;

                    return response.StatusCode == HttpStatusCode.OK;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

即将文件发送到 WCF 服务,但查看帖子的 Wireshark 日志,不会附加 fileStream,仅附加文件名。我还需要做其他事情吗?

c# upload file-upload multipartform-data httpcontent

5
推荐指数
1
解决办法
1万
查看次数

从 HttpClient 的 FormUrlEncodedContent 中提取内容数据

我的内容是:

var content = new Dictionary<string, string>
{
    {"pickup_date", pickupDate.ToString("dd.MM.yyyy HH:mm")},
    {"to_city", "Victoria"},
    {"delivery_company", "4"},
    {"shop_refnum", parameters.Reference},
    {"dimension_side1", "20"},
    {"dimension_side2", "20"},
    {"dimension_side3", "20"},
    {"weight", "5"}
};

var httpContent = new FormUrlEncodedContent(content);
Run Code Online (Sandbox Code Playgroud)

如何从 httpContent 中提取内容?

c# post httpclient httpcontent

5
推荐指数
1
解决办法
2355
查看次数

C#无法将欧元符号打印到文件中(使用Excel打开时)

我有一个get方法进入web api控制器的问题.此方法返回一个HttpResponseMessage对象,该对象具有带有csv文件的HttpContent,该文件包含欧元符号.当方法返回文件时,不会打印欧元符号.该方法的代码如下:

string export = ... //string with fields separed by ';' and with euro symbol
HttpResponseMessage response = new HttpResponseMessage();
UTF8Encoding encoding = new UTF8Encoding();
Byte[] buffer = encoding.GetBytes(export);
response.Content = new ByteArrayContent(buffer);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
response.Content.Headers.ContentLength = export.Length;
response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddDays(1));
return response;
Run Code Online (Sandbox Code Playgroud)

当我打开文件时,欧元符号无法正确显示.你能给我一个答案吗?

非常感谢.

c# excel utf-8 httpcontent

4
推荐指数
1
解决办法
2186
查看次数

使用 moq 模拟 HttpMessageHandler - 如何获取请求的内容?

在决定我想为测试发回什么样的响应之前,有没有办法获取http请求的内容?多个测试将使用此类,每个测试将有多个 http 请求。此代码无法编译,因为 lambda 不是异步的,并且其中有一个等待。我是 async-await 的新手,所以我不确定如何解决这个问题。我曾短暂考虑过拥有多个 TestHttpClientFactories,但这意味着代码重复,因此如果可能,我决定反对它。任何帮助表示赞赏。

public class TestHttpClientFactory : IHttpClientFactory
{
    public HttpClient CreateClient(string name)
    {
        var messageHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);

        messageHandlerMock.Protected()
            .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
            .ReturnsAsync((HttpRequestMessage request, CancellationToken token) =>
            {
                HttpResponseMessage response = new HttpResponseMessage();
                var requestMessageContent = await request.Content.ReadAsStringAsync();

                // decide what to put in the response after looking at the contents of the request

                return response;
            })
            .Verifiable();

        var httpClient = new HttpClient(messageHandlerMock.Object);
        return httpClient;
    }
}
Run Code Online (Sandbox Code Playgroud)

asp.net integration-testing moq async-await httpcontent

4
推荐指数
1
解决办法
1286
查看次数

来自 response.Content.ReadAsStreamAsync() 的流不可随机读取

我正在制作一个 .Net Web API 应用程序,其中以下代码调用我的不同 c# 应用程序以下载文件,然后将其保存在磁盘上。有时一切正常,我得到了文件,但有时下面的代码无法读取流,我可以在其他应用程序中看到远程连接关闭异常。

public async Task<string> GetFilePathAsync(TestModel model)
{
    string filePath = string.Empty;
    var response = await cgRequestHelper.DownloadAsync(model);  

    if (response.IsSuccessStatusCode)
    {                    
        filePath = await SaveCgStreamAsync(cgResponse, serviceModel.FileName);
    }
    return filePath;
}

public async Task<HttpResponseMessage> DownloadAsync(TestModel model)
{            
    if (model == null)
        throw new ArgumentNullException("model");
    if (string.IsNullOrEmpty(model.Url))
        throw new ArgumentNullException("Url");
    if (model.Headers == null)
        throw new ArgumentNullException("Headers");

    HttpResponseMessage response;
    using (HttpClient httpClient = new HttpClient())
    {
        foreach (var header in model.Headers)
        {
            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
        }
        response = await …
Run Code Online (Sandbox Code Playgroud)

c# async-await asp.net-web-api httpcontent httpresponsemessage

3
推荐指数
2
解决办法
2万
查看次数

允许我的Tumblr博客的内容被另一个页面访问

我试图使用我在不同网页上编写的脚本从我的Tumblr博客中复制所有实际内容,但是我在获取内容时遇到了一些麻烦.我的ajax电话如下:

$.ajax({
     url: "http://solacingsavant.tumblr.com/",
     dataType: 'jsonp',
     success: function(data) {
          var elements = $("<div>").html(data)[0].getElementsByTagName("ul")[0].getElementsByTagName("li");
          for(var i = 0; i < elements.length; i++) {
               var theText = elements[i].firstChild.nodeValue;
               alert(theText); // Alert if I got something
              // This is where I'll strip the data for the items I want
          }
     }
});
Run Code Online (Sandbox Code Playgroud)

但因为它是控制台给我一个错误"资源解释为脚本,但转移与MIME类型text/html",我在这里查看并更改meta我的博客的HTML 相应的标签,但<meta http-equiv="Content-Type" content="application/javascript; charset=utf-8" />没有成功

我也尝试过使用dataType: 'html'(这对我来说更有意义)但是我收到了一个控制台错误"来自Access-Control-Allow-Origin不允许来源" ,我也调查过并向我的Tumblr博客添加了一个元标记<meta Access-Control-Allow-Origin="*" />,但又没有成功

这是一个可以使用的jsFiddle

我的方法不起作用,因为Tumblr作为一个整体不允许更改Access-Control吗?如果是这样,我该如何解决这个问题呢?如果没有,我做错了什么?

主要编辑(基于mikedidthis的有用评论)

似乎没有Tubmlr API我无法做到这一点,所以我获得了一个API密钥,现在可以访问API发出的json结果.我能够在控制台中使用API​​密钥获取jsonp对象.我的javascript目前:

$.ajax({ …
Run Code Online (Sandbox Code Playgroud)

api ajax jsonp tumblr httpcontent

1
推荐指数
1
解决办法
1587
查看次数

无法访问 HttpResponseMessage 的正文

我目前正在使用 .NET Core Web App 开发 API 以进行测试,但我一直坚持这个。

实际上,我有这个代码:

namespace CoreWebApp.API.Admin
{
    [Route("api/country")]
    public class CountryController : Controller
    {
        // GET: api/country
        [HttpGet]
        public HttpResponseMessage Get()
        {
            List<Country> countries = Shared.Database.SqlAction.CountriesTable.GetCountries();
            return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(countries), Encoding.UTF8, "application/json") };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是返回一个HttpStatusCode和一个HttpContent。然后我应该在 Postman 上得到它:

[
    {
        "Name":"France"
    },
    {
        "Name":"Germany"
    },
    {
        "Name":"Spain"
    },
    ....
]
Run Code Online (Sandbox Code Playgroud)

状态代码 OK 200


但是,我根本没有得到这个身体,我得到的是:

{
    "version": {
        "major": 1,
        "minor": 1,
        "build": -1,
        "revision": -1,
        "majorRevision": …
Run Code Online (Sandbox Code Playgroud)

c# httpresponse httpcontent asp.net-core-mvc asp.net-core

1
推荐指数
1
解决办法
1253
查看次数