InternalServiceError при попытке опубликовать форму в xamarin AndroidC#

Место общения программистов C#
Ответить
Anonymous
 InternalServiceError при попытке опубликовать форму в xamarin Android

Сообщение Anonymous »

У меня возникли проблемы с моим API в формах xamarin, я все настроил, но это не работает
в форме (запуск приложения на моем физическом телефоне Android), и появляется сообщение Exception: InternalServerError
MainPage.xaml:











MainPage.xaml.cs:
using Newtonsoft.Json;
using PFAG1_2Cars.Core.Entities; // Use the namespace where your Marque class is defined
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace TEST
{
public partial class MainPage : ContentPage
{
private readonly HttpClient _httpClient;

public MainPage()
{
InitializeComponent();
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri("http://192.168.x.x:5050/api/");
}

private async void OnSubmitClicked(object sender, EventArgs e)
{
var marque = new Marque
{
IdMarque = int.Parse(IdMarqueEntry.Text),
NomMarque = NomMarqueEntry.Text
};

var json = JsonConvert.SerializeObject(marque);
var content = new StringContent(json, Encoding.UTF8, "application/json");

try
{
var response = await _httpClient.PostAsync("your", content);
if (response.IsSuccessStatusCode)
{
ResultLabel.Text = "Marque added successfully!";
}
else
{
ResultLabel.Text = $"Error: {response.StatusCode}";
}
}
catch (Exception ex)
{
ResultLabel.Text = $"Exception: {ex.Message}";
}
}
}
}


App.xaml.cs:
using System;
using Xamarin.Forms;
using Microsoft.Extensions.DependencyInjection;
using PFAG1_2Cars.Core.Services;
using PFAG1_2Cars.Data;
using PFAG1_2Cars.Services.Services;
using PFAG1_2Cars.Core;
using PFAG1_2Cars.Data.UnitOfWork;
using PFAG1_2Cars.Data.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;
using PFAG1_2Cars.Core.Repositories;

namespace TEST
{
public partial class App : Application
{
// Static property to hold the service provider
public static IServiceProvider ServiceProvider { get; private set; }

public App()
{
InitializeComponent();

// Setup dependency injection
ConfigureServices();

// Set the main page as a navigation page containing MainPage
MainPage = new NavigationPage(new MainPage());
}

private void ConfigureServices()
{
var services = new ServiceCollection();

var connectionString = "Server=192.168.x.x\\SQLEXPRESS,1433;Database=xxx;User Id=xxx;Password=xxx;";

// Register DbContext from the data layer with the direct connection string
services.AddDbContext
(options =>
options.UseSqlServer(connectionString));
// Register UnitOfWork and other services if needed
services.AddScoped();
services.AddScoped();

// Register repositories
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();

// Build the service provider
ServiceProvider = services.BuildServiceProvider();
}

protected override void OnStart()
{
// Handle when your app starts
}

protected override void OnSleep()
{
// Handle when your app sleeps
}

protected override void OnResume()
{
// Handle when your app resumes
}
}
}


appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=192.168.x.x\\SQLEXPRESS,1433;Database=xxx;User Id=xxx;Password=xxx;Encrypt=False;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ApiBaseUrl": "https://192.168.x.x:5050/api/"
}


Я пробовал в Postman и в своем браузере, и все работает отлично, даже в браузере моего телефона.
[img]https:// i.sstatic.net/Yp4NB7x7.png[/img]

YourController.cs:
using Microsoft.AspNetCore.Mvc;
using PFAG1_2Cars.Core;
using PFAG1_2Cars.Core.Entities;
using PFAG1_2Cars.Core.Repositories;
using PFAG1_2Cars.Core.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Web.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class YourController : ControllerBase
{
private readonly IMarqueService _marqueService;

public YourController(IMarqueService marqueService)
{
_marqueService = marqueService;
}

// GET: api/marque
[HttpGet]
public async Task GetMarques()
{
try
{
var marques = await _marqueService.GetAllMarques();
return Ok(marques);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}

// GET: api/marque/5
[HttpGet("{id}")]
public async Task GetMarque(int id)
{
try
{
var marque = await _marqueService.GetMarqueById(id);
if (marque == null)
{
return NotFound();
}
return Ok(marque);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}

// POST: api/marque
[HttpPost]
public async Task PostMarque(Marque marque)
{
try
{
var newMarque = await _marqueService.CreateMarque(marque);
return CreatedAtAction(nameof(GetMarque), new { id = newMarque.IdMarque }, newMarque);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}

// PUT: api/marque/5
[HttpPut("{id}")]
public async Task PutMarque(int id, Marque marque)
{
try
{
await _marqueService.UpdateMarque(new Marque { IdMarque = id }, marque);
return NoContent();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}

// DELETE: api/marque/5
[HttpDelete("{id}")]
public async Task DeleteMarque(int id)
{
try
{
await _marqueService.DeleteMarqueById(id);
return NoContent();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/786 ... in-android
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»