Support arbitrary 'fetch' arguments

This commit is contained in:
Olivier Lefebvre 2018-03-25 15:12:13 +02:00 committed by Steve Sanderson
parent 0c942ccc76
commit 1626b3b8c8
5 changed files with 47 additions and 10 deletions

View File

@ -7,19 +7,22 @@ const httpClientTypeName = 'BrowserHttpMessageHandler';
const httpClientFullTypeName = `${httpClientNamespace}.${httpClientTypeName}`;
let receiveResponseMethod: MethodHandle;
registerFunction(`${httpClientFullTypeName}.Send`, (id: number, method: string, requestUri: string, body: string | null, headersJson: string | null) => {
sendAsync(id, method, requestUri, body, headersJson);
registerFunction(`${httpClientFullTypeName}.Send`, (id: number, method: string, requestUri: string, body: string | null, headersJson: string | null, fetchArgs: RequestInit | null) => {
sendAsync(id, method, requestUri, body, headersJson, fetchArgs);
});
async function sendAsync(id: number, method: string, requestUri: string, body: string | null, headersJson: string | null) {
async function sendAsync(id: number, method: string, requestUri: string, body: string | null, headersJson: string | null, fetchArgs: RequestInit | null) {
let response: Response;
let responseText: string;
const requestInit = fetchArgs || {};
requestInit.method = method;
requestInit.body = body || undefined;
try {
response = await fetch(requestUri, {
method: method,
body: body || undefined,
headers: headersJson ? (JSON.parse(headersJson) as string[][]) : undefined
});
requestInit.headers = headersJson ? (JSON.parse(headersJson) as string[][]) : undefined;
response = await fetch(requestUri, requestInit);
responseText = await response.text();
} catch (ex) {
dispatchErrorResponse(id, ex.toString());

View File

@ -22,6 +22,8 @@ namespace Microsoft.AspNetCore.Blazor.Browser.Http
static IDictionary<int, TaskCompletionSource<HttpResponseMessage>> _pendingRequests
= new Dictionary<int, TaskCompletionSource<HttpResponseMessage>>();
public const string FetchArgs = "BrowserHttpMessageHandler.FetchArgs";
/// <inheritdoc />
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
@ -36,13 +38,16 @@ namespace Microsoft.AspNetCore.Blazor.Browser.Http
_pendingRequests.Add(id, tcs);
}
request.Properties.TryGetValue(FetchArgs, out var fetchArgs);
RegisteredFunction.Invoke<object>(
$"{typeof(BrowserHttpMessageHandler).FullName}.Send",
id,
request.Method.Method,
request.RequestUri,
request.Content == null ? null : await GetContentAsString(request.Content),
SerializeHeadersAsJson(request));
SerializeHeadersAsJson(request),
fetchArgs);
return await tcs.Task;
}

View File

@ -97,6 +97,15 @@ namespace Microsoft.AspNetCore.Blazor.E2ETest.Tests
Assert.Equal("{\"id\":123,\"name\":\"Bert\"}", _responseBody.Text);
}
[Fact]
public void CanSetRequestReferer()
{
SetValue("request-referrer", "/test-referrer");
IssueRequest("GET", "/api/person/referrer");
Assert.Equal("OK", _responseStatus.Text);
Assert.EndsWith("/test-referrer", _responseBody.Text);
}
private void IssueRequest(string requestMethod, string relativeUri, string requestBody = null)
{
var targetUri = new Uri(_apiServerFixture.RootUri, relativeUri);

View File

@ -1,5 +1,6 @@
@using System.Net
@using System.Net.Http
@using Microsoft.AspNetCore.Blazor.Browser.Http
@inject HttpClient Http
<h1>HTTP request tester</h1>
@ -37,6 +38,11 @@
<button id="add-header" @onclick(AddHeader)>Add</button>
</p>
<p>
<div>Request referrer:</div>
<input id="request-referrer" type="text" value=@requestReferrer @onchange(value => { requestReferrer = (string)value; }) />
</p>
<button id="send-request" @onclick(DoRequest)>Request</button>
@if (responseStatusCode.HasValue)
@ -59,6 +65,7 @@
string method = "GET";
string requestBody = "";
List<RequestHeader> requestHeaders = new List<RequestHeader>();
string requestReferrer = "";
HttpStatusCode? responseStatusCode;
string responseBody;
@ -87,6 +94,14 @@
}
}
if (!string.IsNullOrEmpty(requestReferrer))
{
requestMessage.Properties[BrowserHttpMessageHandler.FetchArgs] = new
{
referrer = requestReferrer
};
}
var response = await Http.SendAsync(requestMessage);
responseStatusCode = response.StatusCode;
responseBody = await response.Content.ReadAsStringAsync();

View File

@ -1,7 +1,6 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
@ -32,6 +31,12 @@ namespace TestServer.Controllers
}
}
[HttpGet("referrer")]
public string GetReferer()
{
return $"The referrer is: {Request.Headers["Referer"].ToString()}";
}
// PUT api/person
[HttpPut]
public Person Put([FromBody, Required] Person person)