标签: httpresponsemessage

值不能为空.参数名称:请求

我正在使用nunit创建一个单元测试,所有这些代码在运行时都能正常工作.

我有HttpResponseMessage下面这个受保护的代码,当它返回时我的控制器会调用它.

但是,错误:

"值不能为空.参数名称:请求"正在显示.

当我检查请求时,实际上是null.

问题:如何编码我的单元测试以返回HttpResponseMessage

错误显示在此行中:

  protected HttpResponseMessage Created<T>(T result) => Request.CreateResponse(HttpStatusCode.Created, Envelope.Ok(result));
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

    [Route("employees")]
    [HttpPost]
    public HttpResponseMessage CreateEmployee([FromBody] CreateEmployeeModel model)
    {
        //**Some code here**//

        return Created(new EmployeeModel
        {
            EmployeeId = employee.Id,
            CustomerId = employee.CustomerId,
            UserId = employee.UserId,
            FirstName = employee.User.FirstName,
            LastName = employee.User.LastName,
            Email = employee.User.Email,

            MobileNumber = employee.MobileNumber,
            IsPrimaryContact = employee.IsPrimaryContact,
            OnlineRoleId = RoleManager.GetOnlineRole(employee.CustomerId, employee.UserId).Id,
            HasMultipleCompanies = EmployeeManager.HasMultipleCompanies(employee.UserId)
        });
    }
Run Code Online (Sandbox Code Playgroud)

c# nunit unit-testing httprequest httpresponsemessage

14
推荐指数
2
解决办法
7358
查看次数

在Dot Net Core代理控制器操作中将HttpResponseMessage转换为ActionResult

以下方法旨在接受Http方法和url,对url执行方法,并将结果响应返回给调用者.它返回ActionResult,因为存在需要处理的错误条件.

目前,该方法只告诉调用者调用是否成功,它不会返回有关来自下游服务器的响应的详细信息.我希望调用者从调用中接收整个响应(包括状态代码,响应正文等).

如何将HttpResponseMessage转换为适合通过ActionResult返回的内容?

    [HttpGet(@"{method}")]
    public async Task<IActionResult> RelayRequest(string method, [FromQuery] string url)
    {

        var httpMethod = new HttpMethod(method);

        Uri uri;
        try
        {
            uri = new Uri(url);
        }
        catch (Exception e)
        {
            return BadRequest("Bad URL supplied: " + e.Message);
        }

        var request = new HttpRequestMessage(httpMethod, uri);

        try
        {
            var response = await _httpClient.SendAsync(request);
            // WANT TO RETURN (ActionResult)response HERE! <<<<<<<<<<

            if (response.IsSuccessStatusCode)
            {
                return Ok();
            }
            return BadRequest(response);
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }

    }
Run Code Online (Sandbox Code Playgroud)

proxy actionresult .net-core httpresponsemessage

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

HttpResponseMessage - 将内容复制到流时出错

我在发布消息时收到以下异常.不知道为什么会这样.有数据点吗?

将内容复制到流时出错

var client = new HttpClient(new HttpClientHandler()
            {
                UseDefaultCredentials = true
            });
            client.BaseAddress = new Uri(Convert.ToString(ConfigurationManager.AppSettings["ServiceMethodUrl"]));
            var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string jsonString = javaScriptSerializer.Serialize(payload);
            var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/JSON");

            HttpResponseMessage response=client.PostAsync("api/event/PostEventStatus", httpContent).Result;

            return response.StatusCode;
Run Code Online (Sandbox Code Playgroud)

json httpresponsemessage

5
推荐指数
0
解决办法
1289
查看次数

Microsoft Edge 忽略内容处置响应标头的 FileName 属性?

我正在将文件发送到浏览器以保存在本地。这在除 Microsoft Edge 之外的所有浏览器中都可以正常工作,它用 guid 替换文件名。必须使用特定文件名下载文件,是否有针对此问题的解释或解决方法?我的回答“不要使用 Edge”将被拒绝。

        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(CreateFile(fileContents))
        };
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = string.Concat(fileName, ".xlsx")
        };
Run Code Online (Sandbox Code Playgroud)

c# microsoft-edge httpresponsemessage

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

ContentDispositionHeaderValue.FileName和ContentDispositionHeaderValue.FileNameStar之间的区别

我们有一个.Net Web应用程序,用户可以在其中下载文件.文件可以包含的文件名可能包含丹麦字符æ,ø和å以及某些外语的其他字符.

我们使用类HttpResponseMessage将ContentDispositionHeaderValue初始化的文件作为"附件"发送.

然而分配

FileName 
Run Code Online (Sandbox Code Playgroud)

属性在IE中不适用于丹麦语字符,但如果我将文件名分配给,则有效

FileNameStar
Run Code Online (Sandbox Code Playgroud)

文件名自动编码为正确的格式.

这样可行:

Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileNameStar = "filename with æ ø and å"
};
Run Code Online (Sandbox Code Playgroud)

但是我找不到任何关于它为何被自动编码的文档,以及哪些浏览器支持此功能.

搜索互联网,给出建议,我应该在将字符串分配给FileNamestar属性之前对其进行编码.但这不是必需的,因为我可以在http跟踪中看到它被正确编码.

所有主流浏览器都支持这个吗?我可以确定文件名是否正确编码?

谢谢圣战

.net url-encoding httpresponsemessage

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

C#OAuth批处理多部分内容响应,如何获取所有内容而不是字符串对象

我收到属于OAuth批处理请求的多部分内容响应:

// batchRequest is a HttpRequestMessage, http is an HttpClient
HttpResponseMessage response = await http.SendAsync(batchRequest);
Run Code Online (Sandbox Code Playgroud)

如果我以全文形式阅读其内容:

string fullResponse = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

它包含以下内容:

--batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16
Content-Type: application/http
Content-Transfer-Encoding: binary

HTTP/1.1 200 OK
DataServiceVersion: 3.0;
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8

{\"odata.metadata\":\"https://graph.windows.net/XXX.onmicrosoft.com/$metadata#directoryObjects/@Element\",\"odata.type\":\"Microsoft.DirectoryServices.User\",\"objectType\":\"User\",\"objectId\":\"5f6851c3-99cc-4a89-936d-4bb44fa78a34\",\"deletionTimestamp\":null,\"accountEnabled\":true,\"signInNames\":[],\"assignedLicenses\":[],\"assignedPlans\":[],\"city\":null,\"companyName\":null,\"country\":null,\"creationType\":null,\"department\":\"NRF\",\"dirSyncEnabled\":null,\"displayName\":\"dummy1 Test\",\"facsimileTelephoneNumber\":null,\"givenName\":\"dummy1\",\"immutableId\":null,\"isCompromised\":null,\"jobTitle\":\"test\",\"lastDirSyncTime\":null,\"mail\":null,\"mailNickname\":\"dummy1test\",\"mobile\":null,\"onPremisesSecurityIdentifier\":null,\"otherMails\":[],\"passwordPolicies\":null,\"passwordProfile\":{\"password\":null,\"forceChangePasswordNextLogin\":true,\"enforceChangePasswordPolicy\":false},\"physicalDeliveryOfficeName\":null,\"postalCode\":null,\"preferredLanguage\":null,\"provisionedPlans\":[],\"provisioningErrors\":[],\"proxyAddresses\":[],\"refreshTokensValidFromDateTime\":\"2016-12-02T08:37:24Z\",\"showInAddressList\":null,\"sipProxyAddress\":null,\"state\":\"California\",\"streetAddress\":null,\"surname\":\"Test\",\"telephoneNumber\":\"666\",\"thumbnailPhoto@odata.mediaEditLink\":\"directoryObjects/5f6851c3-99cc-4a89-936d-4bb44fa78a34/Microsoft.DirectoryServices.User/thumbnailPhoto\",\"usageLocation\":null,\"userPrincipalName\":\"dummy1test@XXX.onmicrosoft.com\",\"userType\":\"Member\"}
--batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16
Content-Type: application/http
Content-Transfer-Encoding: binary

HTTP/1.1 200 OK
DataServiceVersion: 3.0;
Content-Type: application/json;odata=minimalmetadata;streaming=true;charset=utf-8

{\"odata.metadata\":\"https://graph.windows.net/XXX.onmicrosoft.com/$metadata#directoryObjects/@Element\",\"odata.type\":\"Microsoft.DirectoryServices.User\",\"objectType\":\"User\",\"objectId\":\"dd35d761-e6ed-44e7-919f-f3b1e54eb7be\",\"deletionTimestamp\":null,\"accountEnabled\":true,\"signInNames\":[],\"assignedLicenses\":[],\"assignedPlans\":[],\"city\":null,\"companyName\":null,\"country\":null,\"creationType\":null,\"department\":null,\"dirSyncEnabled\":null,\"displayName\":\"Max Admin\",\"facsimileTelephoneNumber\":null,\"givenName\":null,\"immutableId\":null,\"isCompromised\":null,\"jobTitle\":null,\"lastDirSyncTime\":null,\"mail\":null,\"mailNickname\":\"maxadmin\",\"mobile\":null,\"onPremisesSecurityIdentifier\":null,\"otherMails\":[],\"passwordPolicies\":null,\"passwordProfile\":null,\"physicalDeliveryOfficeName\":null,\"postalCode\":null,\"preferredLanguage\":null,\"provisionedPlans\":[],\"provisioningErrors\":[],\"proxyAddresses\":[],\"refreshTokensValidFromDateTime\":\"2016-12-05T15:11:51Z\",\"showInAddressList\":null,\"sipProxyAddress\":null,\"state\":null,\"streetAddress\":null,\"surname\":null,\"telephoneNumber\":null,\"thumbnailPhoto@odata.mediaEditLink\":\"directoryObjects/dd35d761-e6ed-44e7-919f-f3b1e54eb7be/Microsoft.DirectoryServices.User/thumbnailPhoto\",\"usageLocation\":null,\"userPrincipalName\":\"maxadmin@XXX.onmicrosoft.com\",\"userType\":\"Member\"}
--batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16--
Run Code Online (Sandbox Code Playgroud)

我需要将所有这些内容作为对象(例如经典的HttpResponseMessage,而不是简单的字符串)来获取,以便将HTTP返回代码,JSON内容等作为属性并能够将其处理。

我知道如何分别阅读所有这些内容,但是我无法弄清楚如何将它们作为对象获取,我仅成功获取了字符串内容:

var multipartContent = await response.Content.ReadAsMultipartAsync();
foreach (HttpContent currentContent in multipartContent.Contents) {
     var testString = currentContent.ReadAsStringAsync();
     // How to get this content as an exploitable object?
}
Run Code Online (Sandbox Code Playgroud)

在我的示例中,testString包含: …

c# oauth httpresponsemessage

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

如何将 System.Net.Http.HttpResponseMessage 转换为 System.Web.Mvc.ActionResult

我正在编写简单的代理应用程序,它获取“URL 地址”,如“/xController/xMethod”,并通过 HttpClient 从另一个 Web 应用程序获取结果并显示结果。

我的方法:

public ActionResult Index(string urlAddress)
{
   var data = "";
   if (Request.ContentLength > 0 && httpRequestMessage != null)
       data = httpRequestMessage.Content.ReadAsStringAsync().Result;

    using (var client = new HttpClient())
    {
      // fill header and set target site url 

      // Make Post Data
      var buffer = System.Text.Encoding.UTF8.GetBytes(data);
      var byteContent = new ByteArrayContent(buffer);
      if (!String.IsNullOrWhiteSpace(Request.ContentType) && !String.IsNullOrEmpty(Request.ContentType))
           byteContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue(Request.ContentType);

       // make query string ....

       // sending request to target site         
       HttpResponseMessage response = null;
       if (Request.HttpMethod.ToUpper() …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc httpclient actionresult httpresponsemessage

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

来自 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万
查看次数

HttpResponseMessage 的处理是调用请求流的处理

我有一个方法,它采用 Stream 参数并将其传递给服务器

public async Task<string> Execute(Stream archive)
    {
        archive.Seek(0, SeekOrigin.Begin);
        using var content = new MultipartFormDataContent();
        content.Add(new StreamContent(archive), "file1", "file1");
        var result = "";
        using (var response = await _client.PostAsync(_uri, content))
        {
            if (response.IsSuccessStatusCode)
            {
                var stringResult = await response.Content.ReadAsStringAsync();
                result = stringResult;
            }
        }
        // here archive is already disposed
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

现在我实现这个方法的重试策略。如果调用此方法的外部代码得到“”结果,则它会尝试再次调用此方法。但档案是在那一刻处理的。我看到存档流在处理响应后立即被处理。为什么?如果在这个方法之后需要外部流参数怎么办?

c# httpclient .net-core httpresponsemessage

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

将HttpResponseMessage转换为XML到Object

我已经为我的对象定义了序列化idAssignmentResult.但是,如何将IS XML的HttpResponseMessage转换为它的类?我收到一个错误:

"System.Net.Http.HttpContent"类型的值无法转换为"System.Xml.XmlReader"

我会做vb.net和c#

vb.net

    Dim response As New HttpResponseMessage()
        Try
            Using client As New HttpClient()
                Dim request As New HttpRequestMessage(HttpMethod.Post, "url")
                request.Content = New StringContent(stringWriter.ToString, Encoding.UTF8, "application/xml")

                response = client.SendAsync(request).Result
            End Using
        Catch ex As Exception
            lblerror.Text = ex.Message.ToString
        End Try
    Dim responseString = response.Content

    Dim xmls As New XmlSerializer(GetType(idAssignmentResult))
    Dim assignmentResult As New idAssignmentResult()
    xmls.Deserialize(responseString, assignmentResult) /// cannot convert HttpContent to XmlReader
Run Code Online (Sandbox Code Playgroud)

C#

    StringWriter stringWriter = new StringWriter();
    XmlSerializer serializer = new XmlSerializer(typeof(personV3R));
    personV3R person = …
Run Code Online (Sandbox Code Playgroud)

c# xml vb.net httpresponsemessage

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