locked
Blazor Webassembly .Net 5, able to upload DataUri to Server via PostAsJsonAsync on Firefox windows but not on Android & Safari Mobile? RRS feed

  • Question

  • User-2611850 posted

    Hello Everyone,

    In my Blazor App I am able to upload my jpg which I transfer to an DataUri in Javascript via PostAsJsonAsync to my Server Api on Windows but not Mobile. Any help is greatly appreciated. It is very difficult because I cannot debug on Mobile. The Code seems to Run up to PostAsJsonAsync and then crash in there. DataUri comes back correct from Javascript. The Image is only 184Kb. Jason seems fine as well. The WebApi is never reached. This problems are all only on mobile, the same code and procedures run fine on windows.

    Thanks a lot, Kind Blessings, Andreas

    Blazor Client Code:

    @page "/captureresource"
    @inject JsWebcamWrapper jsWebcam
    @inject JsInterop jsInterop
    @inject IToastService toastService
    ...
    <input id="captureresourceid" type="file" name="image" @onchange="CamperaTakePicture">
    <img id="imgid" />
    <div class="container">
        <div class="card-deck">
            @foreach (var bookresult in BookResults)
            {
                <CaptureItem Model="bookresult" />
            }
        </div>
    </div>
    @code{
        public List<BookModel> BookResults { get; set; } = new List<BookModel>();
        public async Task CamperaTakePicture()
        {
            try
            {
                BookResults = new();
                this.StateHasChanged();
                UploadedFile uploadedFile = new();
                uploadedFile.FileContentDataUri = await jsWebcam.GetDataUri();
    
                var response = await Http.PostAsJsonAsync<UploadedFile>("FileUpload/GetISBNBookInfo", uploadedFile);
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    toastService.ShowError((await response.Content.ReadFromJsonAsync<Error>()).Exception?.ToString());
                }
                else
                {
                    BookResults = await response.Content.ReadFromJsonAsync<List<BookModel>>();
                    this.StateHasChanged();
                }
                await jsWebcam.ClearImage("imgid");
            }
            catch (Exception ex)
            {
                toastService.ShowError("Exception Thrown in CamperaTakePicture: " + ex.ToString());
                Serilog.Log.Error(ex, "CaptureResource.razor: Exception Thrown in CamperaTakePicture: ");
            }
        }
    }

    JavaScript Code:

    export async function getdatauri() {
        return new Promise((resolve, reject) => {
            var file = document.getElementById('captureresourceid').files[0];
            const reader = new FileReader();
    
            reader.onload = res => {
                resolve(res.target.result);
            };
            reader.onerror = err => reject(err);
    
            reader.readAsDataURL(file);
        });
    }

    Server Code:

    [Route("GetISBNBookInfo")]
    [HttpPost]
    public async Task<ActionResult<List<BookModel>>> GetISBNBookInfo(UploadedFile uploadedFile)
    {
        try
        {
            var imageBytes = Convert.FromBase64String(uploadedFile.FileContentDataUri.Split(',')[1]);
            using (Stream stream = new MemoryStream(imageBytes))
            {
                List<BookModel> result = new();
                .....
                if (result.Count > 0)
                    return Ok(result);
                return NotFound(new Error { Id = 1, Exception = "....please try again." });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in FileUploadController");
            return NotFound(new Error { Id = 1, Exception = "Exception thrown in GetISBNBookInfo." + ex.ToString() });
        }
    }

    Exception Message:

    System.Text.Json.JsonException: ExpectedJsonTokens Path: $ | LineNumber: 0 | BytePositionInLine: 0. ---> System.Text.Json.JsonReaderException: ExpectedJsonTokens LineNumber: 0 | BytePositionInLine: 0.    at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)    at System.Text.Json.Utf8JsonReader.Read()    at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.List`1[[ReneeMcGuire.Shared.Models.BookModel, ReneeMcGuire.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)    Exception_EndOfInnerExceptionStack    at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)    at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.List`1[[ReneeMcGuire.Shared.Models.BookModel, ReneeMcGuire.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)    at System.Text.Json.JsonSerializer.ReadCore[List`1](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)    at System.Text.Json.JsonSerializer.ReadCore[List`1](JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& state, JsonConverter converterBase)    at System.Text.Json.JsonSerializer.<ReadAsync>d__20`1[[System.Collections.Generic.List`1[[ReneeMcGuire.Shared.Models.BookModel, ReneeMcGuire.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()    at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__3`1[[System.Collections.Generic.List`1[[ReneeMcGuire.Shared.Models.BookModel, ReneeMcGuire.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()    at ReneeMcGuire.Client.Pages.CaptureResource.CamperaTakePicture()

    Details on ExpectedJsonTokens JsonException from Sourcecode:

    /// <summary>
    /// Read the next JSON token from input source.
    /// </summary>
    /// <returns>True if the token was read successfully, else false.</returns>
    /// <exception cref="JsonException">
    /// Thrown when an invalid JSON token is encountered according to the JSON RFC
    /// or if the current depth exceeds the recursive limit set by the max depth.
    /// </exception>
    public bool Read()
    {
    	bool retVal = _isMultiSegment ? ReadMultiSegment() : ReadSingleSegment();
    
    	if (!retVal)
    	{
    		if (_isFinalBlock && TokenType == JsonTokenType.None)
    		{
    			ThrowHelper.ThrowJsonReaderException(ref this, ExceptionResource.ExpectedJsonTokens);
    		}
    	}
    	return retVal;
    }

    Wednesday, March 24, 2021 5:52 PM

Answers

  • User-474980206 posted

    you should be able to remote debug the mobile browser via webkit remote debug (safari requires a Mac with safari). you could then see the network traffic in the debug and determine more. you would also get console errors and prints.

    I only used a Mac, but windows chrome is supposed to work also. 

    note: in web assembly HttpClient just uses javascript interop to do the network calls.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 26, 2021 1:55 AM